Hello,
I am trying to solve the maximum sum subsequence
problem, using topdown
approach. I am able to come up with an O(n^3)
solution, but want an O(n^2)
solution. The reason I’m not going with the bottom up
approach (O(n^2))
is that I am fairly new to DP, and topdown approaches are really intuitive and much easier to come up with.
Here is the code(recursive). We can see that there are three different variables and hence we need to come up with a DP table like
dp[i][prev][sum]
int max_sum_sub(int arr[], int i, int n, int prev, int sum)
{
// Base case: nothing is remaining
if (i == n)
return sum;
// exclude the current element
int exclude = max_sum_sub(arr, i + 1, n, prev, sum);
// case 2: include the current element if it is greater
// than previous element
int include = sum;
if (arr[i] > prev)
incl = max_sum_sub(arr, i + 1, n, arr[i], sum + arr[i]);
// return maximum of above two choices
return max(incl, excl);
}
Please help.
Thanks