Posts Max Sum Increasing Subsequence (geeksforgeeks - SDE Sheet)
Post
Cancel

Max Sum Increasing Subsequence (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an array of n positive integers. Find the sum of the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in strictly increasing order i.e. a strictly increasing subsequence.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution
{
    // Method to find the maximum sum of an increasing subsequence
    public int maxSumIS(int arr[], int n)
    {

        int maxSum = 0;

        // dp[i] represents the maximum sum of an increasing subsequence ending with arr[i]
        int[] dp = new int[n];

        // dp[i] will be at least equal to that element itself
        for(int i = 0; i < n; i++)
            dp[i] = arr[i];

        // Initialize maxSum with the first element of dp
        maxSum = dp[0];

        // Loop over the array to find the maximum sum increasing subsequence
        for(int i = 1; i < n; i++){

            // Check all previous elements to find subsequences that can be extended by arr[i]
            for(int j = 0; j < i; j++){

                // If arr[i] is greater than arr[j], we can extend the subsequence ending at j
                if(arr[i] > arr[j]){

                    // Update dp[i] to reflect the maximum possible sum ending at arr[i]
                    dp[i] = Math.max(dp[i], dp[j] + arr[i]);

                }
            }

            // Update maxSum with the maximum value found so far
            maxSum = Math.max(maxSum, dp[i]);
        }

        return maxSum;
    }
}
This post is licensed under CC BY 4.0 by the author.