17. Max Sum Increasing Subsequence
β GFG solution to the Max Sum Increasing Subsequence problem: find maximum sum of strictly increasing subsequence using dynamic programming and optimized approaches. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[] consisting of positive integers. Your task is to find the maximum sum of a subsequence such that the elements of the subsequence form a strictly increasing sequence.
In other words, among all strictly increasing subsequences of the array, return the one with the largest possible sum.
π Examples
Example 1
Input: arr[] = [1, 101, 2, 3, 100]
Output: 106
Explanation: The maximum sum of an increasing sequence is obtained from [1, 2, 3, 100].Example 2
Input: arr[] = [4, 1, 2, 3]
Output: 6
Explanation: The maximum sum of an increasing sequence is obtained from [1, 2, 3].Example 3
π Constraints
$1 \le \text{arr.size()} \le 10^3$
$1 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses Dynamic Programming to efficiently build up the maximum sum for increasing subsequences ending at each position:
Dynamic Programming Approach
Initialize DP Array:
Create a
dp[]array wheredp[i]represents the maximum sum of increasing subsequence ending at indexi.Initially, set
dp[i] = arr[i]as each element can form a subsequence by itself.
Build DP Table:
For each position
i, iterate through all previous positionsj(wherej < i).If
arr[j] < arr[i](strictly increasing condition), updatedp[i] = max(dp[i], dp[j] + arr[i]).This means we can extend the subsequence ending at
jby includingarr[i].
Track Maximum:
Maintain a variable
resto track the maximum value in thedp[]array.Update
resafter computing eachdp[i].
Return Result:
The answer is the maximum value in the
dp[]array, representing the largest sum achievable.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(nΒ²), where n is the size of the array. We use nested loops to compare each element with all previous elements to build the DP table.
Expected Auxiliary Space Complexity: O(n), as we use a DP array of size n to store the maximum sum ending at each position.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated