I am solving this question on leetcode link
This is my working solution using an unordered map which gives me a TLE while using a vector of vectors passes all test cases.
They both work on the same logic then why does using an unordered map give me a TLE ?
class Solution {
public:
int longestArithSeqLength(vector<int>& a) {
// vector of umaps
vector<unordered_map<int, int>> aux(a.size());
// iterate array
int n = a.size();
int ans = INT_MIN;
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < i; ++j)
{
int currdiff = a[j] - a[i];
unordered_map<int, int> &umapj = aux[j];
unordered_map<int, int> &umapi = aux[i];
umapi[currdiff] = umapj[currdiff] + 1;
if(umapi[currdiff] > ans)
{
ans = umapi[currdiff];
}
}
}
return ans+1;
}
};
code using vector:
class Solution {
public:
int longestArithSeqLength(vector<int>& A) {
int n = A.size();
vector<vector<int>> dp(n, vector<int> (1005, 1));
int maxLen = 1;
for(int i=1;i<n;i++)
{
for(int j=0;j<i;j++)
{
int d = A[j] - A[i];
dp[i][d + 500] = dp[j][d + 500] + 1;
maxLen = max(maxLen, dp[i][d + 500]);
}
}
return maxLen;
}
};