There is a question to basically find the largest sum in an array, such that no two elements are chosen adjacent to each other. The concept is to recursively calculate the sum, while considering and not considering every element, and skipping an element depending on whether the previous element was selected or not.
I understand that this problem requires the use of Dynamic Programming, but doing so still gives me a TLE. Although my code is very similar to the solution code, I cannot figure out why am I getting a TLE (>1.9 seconds). The constraints are given that n >= 1, and so initialising the DP array to 0's shouldn't be a problem in my opinion.
Algorithmically, I think that the two codes below achieve the same task: processing each element, then either considering it in the sum (in this case, the next recursive call is done for the (i+2)th
element), or not considering the element in the sum (the next recursive call is done for the (i+1)th
element.
Note:
vector<int>&B
-> denotes the array elements.int K
-> denotes the number of elements whose sum is to be takenint N
-> total number of elements in the vector.int i
-> keep track of which element is currently being processed
Here is my code:
class Solution{
public:
long long dp[1010][510];
long long maxSum(vector<int> &B, int K, int N, int i){
if (K == 0) return 0;
else if(i >= N){
return INT_MIN;
}
else{
if (dp[i][K] != INT_MIN) return dp[i][K];
dp[i][K] = max(maxSum(B, K, N, i+1), B[i] + maxSum(B, K-1, N, i+2));
return dp[i][K];
}
}
long long maximumBeauty(int N, int K, vector<int> &B){
int i = 0;
for (int i = 0; i<1010; i++){
for (int j = 0; j<510; j++){
dp[i][j] = INT_MIN;
}
}
return maxSum(B, K, N, i);
}
};
and here is the given solution:
class Solution{ public: long long dp(int i, int j, int N, int K, vector<int> &B, vector<vector<long long>> &cache){ if(j >= K){ return 0; } if(i >= N){ return -1e15; } if(cache[i][j] != -1e18){ return cache[i][j]; } cache[i][j] = max((long long )B[i] + dp(i + 2, j + 1, N, K, B, cache), dp(i + 1, j, N, K, B, cache)); return cache[i][j]; } long long maximumBeauty(int N, int K, vector<int> &B){ vector<vector<long long>> cache(N, vector<long long> (K, -1e18)); long long ans = dp(0, 0, N, K, B, cache); return ans; } };
I've tried initialising the DP array to different values (such as initialising it with INT_MIN's instead of 0's), but I'm still getting a TLE. Please help me figure out the reason for getting a TLE in the first code, while the second code does not.
EDIT If you want to test the code out and whether it's giving a TLE error, you can try submitting the code here: question-link