Given an array a[] consisting of N integers, the task is to perform the following operations:
Examples:
_Input: _N = 3, a[] = {-1, 3, 4}
Output:_ 17_
Explanation:
The subsequence {-1, 3, 4} maximizes the sum = 1(-1) + 2(3) + 3(4) = 17
Input:_ N = 5, a[] = {-1, -9, 0, 5, -7}_
Output:_ 14_
Explanation:
The subsequence {-1, 0, 5} maximizes the sum = 1(-1) + 2(0) + 3(5) = 14
**Naive Approach: **The simplest approach to solve the problem is to generate all possible subsequences from the array and calculate the sum for each subsequence. Finally, find the maximum sum.
_Time Complexity: _O(N3)
Auxiliary Space:_ O(N)_
**Efficient Approach: **The above approach can be optimized by using Dynamic Programming. Follow the steps below to solve the problem:
a[i] * j + maximumSum(j + 1, i + 1)
maximumSum(j, i + 1)
dp[i][j] = max(a[i] * j + maximumSum(j + 1, i + 1), maximumSum(j, i + 1))
Below is the implementation of the above approach:
// Java program to implement
// the above approach
**import**
java.util.*;
**public**
**class**
GFG {
// Function to select the array elements to
// maximize the sum of the selected elements
**public**
**static**
**int**
maximumSum(``**int**``[] a,
**int**
count,
**int**
index,
**int**
n,
**int**``[][] dp)
{
// If the entire array
// is solved
**if**
(index == n)
**return**
0``;
// Memoized subproblem
**if**
(dp[index][count] != -``1``)
**return**
dp[index][count];
// Calculate sum considering the
// current element in the subsequence
**int**
take_element
= a[index] * count
+ maximumSum(a, count +
1``,
index +
1``, n, dp);
// Calculate sum without considering the
// current element in the subsequence
**int**
dont_take
= maximumSum(a, count, index +
1``, n, dp);
// Update the maximum of the above sums
// in the dp[][] table
**return**
dp[index][count]
= Math.max(take_element, dont_take);
}
// Driver Code
**public**
**static**
**void**
main(String args[])
{
**int**
n =
5``;
**int**
a[] = { -``1``, -``9``,
0``,
5``, -``7
};
// Initialize the dp array
**int**
dp[][] =
**new**
**int**``[n +
1``][n +
1``];
**for**
(``**int**
i[] : dp)
Arrays.fill(i, -``1``);
System.out.println(maximumSum(a,
1``,
0``, n, dp));
}
}
Output:
14
Time Complexity:_ O(N2)_
Auxiliary Space:_ O(N2)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#arrays #dynamic programming #recursion #memoization #subsequence