Help me out in this problem

my code is giving tle on leetcode


kindly see it
o(n^2) must be accepted as per my code

@aman212yadav kindly see it

its not o(n^2) bro.

try dynamic programming…


class Solution {
public:
    int longestArithSeqLength(vector<int>& A) {
        int n=A.size();
        vector< vector<int> > dp(n,vector<int>(1005,0));
        int ans=0;
        for(int i=0;i<n;i++){
            
            for(int j=0;j<i;j++){
                int diff=A[i]-A[j]+500;
                int &x=dp[i][diff],&y=dp[j][diff];
                x=max(x,1+y);
                ans=max(ans,1+x);
            }
        }
        return ans;
    }
};

dp state is simple.
dp[i][diff] =longest ap when array [0…i] is considered and common difference is diff

@aman212yadav why it is not o(n^2)

there r 4 nested loops. .

@aman212yadav in solution of faang same solution is there?
but they map<int,list> insplace of vector?

i m not sure whats there solution is but yeah map can be used in place of 2 d vector.

@aman212yadav
is there is any solution in o(n^2) approach?

dp… …

@aman212yadav i didnot understand your dp logic?
can you explain me ?

refer this–>link

@aman212yadav //can you send me number…///////

@shivammishra20121999
no bro, i cant…
is the approach still not clear?

@aman212yadav
no bro i didnot get it

the idea is exaclty same as longest increasing subsequence.

check this out->longest ap