Printing Maximum Sum Increasing Subsequence

The Maximum Sum Increasing Subsequence problem is to find the maximum sum subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.

Examples: 

Input:  [1, 101, 2, 3, 100, 4, 5]
Output: [1, 2, 3, 100]

Input:  [3, 4, 5, 10]
Output: [3, 4, 5, 10]

Input:  [10, 5, 4, 3]
Output: [10]

Input:  [3, 2, 6, 4, 5, 1]
Output: [3, 4, 5]

In previous post, we have discussed about Maximum Sum Increasing Subsequence problem. However, the post only covered code related to finding maximum sum of increasing subsequence, but not to the construction of subsequence. In this post, we will discuss how to construct Maximum Sum Increasing Subsequence itself.
Let arr[0..n-1] be the input array. We define vector L such that L[i] is itself is a vector that stores Maximum Sum Increasing Subsequence of arr[0..i] that ends with arr[i]. Therefore for an index i, L[i] can be recursively written as 
 

L[0] = {arr[0]}
L[i] = {MaxSum(L[j])} + arr[i] where j < i and arr[j] < arr[i]
     = arr[i], if there is no j such that arr[j] < arr[i]


For example, for array [3, 2, 6, 4, 5, 1], 

L[0]: 3
L[1]: 2
L[2]: 3 6
L[3]: 3 4
L[4]: 3 4 5
L[5]: 1

Below is the implementation of the above idea – 



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Dynamic Programming solution to construct
   Maximum Sum Increasing Subsequence */
#include <iostream>
#include <vector>
using namespace std;
 
// Utility function to calculate sum of all
// vector elements
int findSum(vector<int> arr)
{
    int sum = 0;
    for (int i : arr)
        sum += i;
    return sum;
}
 
// Function to construct Maximum Sum Increasing
// Subsequence
void printMaxSumIS(int arr[], int n)
{
    // L[i] - The Maximum Sum Increasing
    // Subsequence that ends with arr[i]
    vector<vector<int> > L(n);
 
    // L[0] is equal to arr[0]
    L[0].push_back(arr[0]);
 
    // start from index 1
    for (int i = 1; i < n; i++) {
        // for every j less than i
        for (int j = 0; j < i; j++) {
            /* L[i] = {MaxSum(L[j])} + arr[i]
            where j < i and arr[j] < arr[i] */
            if ((arr[i] > arr[j])
                && (findSum(L[i]) < findSum(L[j])))
                L[i] = L[j];
        }
 
        // L[i] ends with arr[i]
        L[i].push_back(arr[i]);
 
        // L[i] now stores Maximum Sum Increasing
        // Subsequence of arr[0..i] that ends with
        // arr[i]
    }
 
    vector<int> res = L[0];
 
    // find max
    for (vector<int> x : L)
        if (findSum(x) > findSum(res))
            res = x;
 
    // max will contain result
    for (int i : res)
        cout << i << " ";
    cout << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 6, 4, 5, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // construct and print Max Sum IS of arr
    printMaxSumIS(arr, n);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Dynamic Programming solution to construct
Maximum Sum Increasing Subsequence */
import java.util.*;
 
class GFG {
 
    // Utility function to calculate sum of all
    // vector elements
    static int findSum(Vector<Integer> arr)
    {
        int sum = 0;
        for (int i : arr)
            sum += i;
        return sum;
    }
 
    // Function to construct Maximum Sum Increasing
    // Subsequence
    static void printMaxSumIs(int[] arr, int n)
    {
 
        // L[i] - The Maximum Sum Increasing
        // Subsequence that ends with arr[i]
        @SuppressWarnings("unchecked")
        Vector<Integer>[] L = new Vector[n];
 
        for (int i = 0; i < n; i++)
            L[i] = new Vector<>();
 
        // L[0] is equal to arr[0]
        L[0].add(arr[0]);
 
        // start from index 1
        for (int i = 1; i < n; i++) {
 
            // for every j less than i
            for (int j = 0; j < i; j++) {
 
                /*
                * L[i] = {MaxSum(L[j])} + arr[i]
                  where j < i and arr[j] < arr[i]
                */
                if ((arr[i] > arr[j])
                    && (findSum(L[i]) < findSum(L[j]))) {
                    for (int k : L[j])
                        if (!L[i].contains(k))
                            L[i].add(k);
                }
            }
 
            // L[i] ends with arr[i]
            L[i].add(arr[i]);
 
            // L[i] now stores Maximum Sum Increasing
            // Subsequence of arr[0..i] that ends with
            // arr[i]
        }
 
        Vector<Integer> res = new Vector<>(L[0]);
        // res = L[0];
 
        // find max
        for (Vector<Integer> x : L)
            if (findSum(x) > findSum(res))
                res = x;
 
        // max will contain result
        for (int i : res)
            System.out.print(i + " ");
        System.out.println();
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 3, 2, 6, 4, 5, 1 };
        int n = arr.length;
 
        // construct and print Max Sum IS of arr
        printMaxSumIs(arr, n);
    }
}
 
// This code is contributed by
// sanjeev2552

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Dynamic Programming solution to construct
# Maximum Sum Increasing Subsequence */
 
# Utility function to calculate sum of all
# vector elements
 
 
def findSum(arr):
 
    summ = 0
    for i in arr:
        summ += i
    return summ
 
# Function to construct Maximum Sum Increasing
# Subsequence
 
 
def printMaxSumIS(arr, n):
 
    # L[i] - The Maximum Sum Increasing
    # Subsequence that ends with arr[i]
    L = [[] for i in range(n)]
 
    # L[0] is equal to arr[0]
    L[0].append(arr[0])
 
    # start from index 1
    for i in range(1, n):
 
        # for every j less than i
        for j in range(i):
 
            # L[i] = {MaxSum(L[j])} + arr[i]
            # where j < i and arr[j] < arr[i]
            if ((arr[i] > arr[j]) and
                    (findSum(L[i]) < findSum(L[j]))):
                for e in L[j]:
                    if e not in L[i]:
                        L[i].append(e)
 
        # L[i] ends with arr[i]
        L[i].append(arr[i])
 
        # L[i] now stores Maximum Sum Increasing
        # Subsequence of arr[0..i] that ends with
        # arr[i]
 
    res = L[0]
 
    # find max
    for x in L:
        if (findSum(x) > findSum(res)):
            res = x
 
    # max will contain result
    for i in res:
        print(i, end=" ")
 
 
# Driver Code
arr = [3, 2, 6, 4, 5, 1]
n = len(arr)
 
# construct and prMax Sum IS of arr
printMaxSumIS(arr, n)
 
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Dynamic Programming solution to construct
Maximum Sum Increasing Subsequence */
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Utility function to calculate sum of all
    // vector elements
    static int findSum(List<int> arr)
    {
        int sum = 0;
        foreach(int i in arr) sum += i;
        return sum;
    }
 
    // Function to construct Maximum Sum Increasing
    // Subsequence
    static void printMaxSumIs(int[] arr, int n)
    {
 
        // L[i] - The Maximum Sum Increasing
        // Subsequence that ends with arr[i]
        List<int>[] L = new List<int>[ n ];
 
        for (int i = 0; i < n; i++)
            L[i] = new List<int>();
 
        // L[0] is equal to arr[0]
        L[0].Add(arr[0]);
 
        // start from index 1
        for (int i = 1; i < n; i++) {
 
            // for every j less than i
            for (int j = 0; j < i; j++) {
 
                /*
                * L[i] = {MaxSum(L[j])} + arr[i]
                where j < i and arr[j] < arr[i]
                */
                if ((arr[i] > arr[j])
                    && (findSum(L[i]) < findSum(L[j]))) {
                    foreach(int k in
                                L[j]) if (!L[i].Contains(k))
                        L[i]
                            .Add(k);
                }
            }
 
            // L[i] ends with arr[i]
            L[i].Add(arr[i]);
 
            // L[i] now stores Maximum Sum Increasing
            // Subsequence of arr[0..i] that ends with
            // arr[i]
        }
 
        List<int> res = new List<int>(L[0]);
        // res = L[0];
 
        // find max
        foreach(List<int> x in L) if (findSum(x)
                                      > findSum(res)) res
            = x;
 
        // max will contain result
        foreach(int i in res) Console.Write(i + " ");
        Console.WriteLine();
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 3, 2, 6, 4, 5, 1 };
        int n = arr.Length;
 
        // construct and print Max Sum IS of arr
        printMaxSumIs(arr, n);
    }
}
 
// This code is contributed by PrinciRaj1992

chevron_right


Output

3 4 5 

We can optimize the above DP solution by removing findSum() function. Instead, we can maintain another vector/array to store sum of maximum sum increasing subsequence that ends with arr[i]. The implementation can be seen here.
Time complexity of above Dynamic Programming solution is O(n2). 
Auxiliary space used by the program is O(n2).

Approach 2: (Using Dynamic Programming Using O(N) space

The above approach covered how to construct a Maximum Sum Increasing Subsequence in O(N2) time and O(N2) space. In this approach, we will optimize the Space complexity and construct the Maximum Sum Increasing Subsequence in O(N2)  time and O(N) space.

  • Let arr[0..n-1] be the input array. 
  • We define a vector of pairs L such that L[i] first stores the Maximum Sum Increasing Subsequence of arr[0..i] that ends with arr[i] and L[i].second stores the index of the previous element used for generating the sum.
  • As the first element does not have any previous element hence its index would be -1 in L[0].

For example,

array = [3, 2, 6, 4, 5, 1]

L[0]: {3, -1}
L[1]: {2,  1}
L[2]: {9,  0}
L[3]: {7, 0}
L[4]: {12, 3}
L[5]: {1, 5}

As we can see above, the value of the Maximum Sum Increasing Subsequence is 12. To construct the actual Subsequence we will use the index stored in L[i].second. The steps to construct the Subsequence is shown below:

  • In a vector result, store the value of the element where the Maximum Sum Increasing Subsequence was found (i.e at currIndex = 4). So in the result vector, we will add arr[currIndex].
  • Update the currIndex to L[currIndex].second and repeat step 1 until currIndex is not -1 or it does not changes (i.e currIndex == previousIndex).
  • Display the elements of the result vector in reverse order.

Below is the implementation of the above idea :

C++14

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Dynamic Programming solution to construct
Maximum Sum Increasing Subsequence */
#include <bits/stdc++.h>
using namespace std;
 
// Function to construct and print the Maximum Sum
// Increasing Subsequence
void constructMaxSumIS(vector<int> arr, int n)
{
    // L[i] stores the value of Maximum Sum Increasing
    // Subsequence that ends with arr[i] and the index of
    // previous element used to construct the Subsequence
    vector<pair<int, int> > L(n);
 
    int index = 0;
    for (int i : arr) {
        L[index] = { i, index };
        index++;
    }
 
    // Set L[0].second equal to -1
    L[0].second = -1;
 
    // start from index 1
    for (int i = 1; i < n; i++) {
        // for every j less than i
        for (int j = 0; j < i; j++) {
            if (arr[i] > arr[j]
                and L[i].first < arr[i] + L[j].first) {
                L[i].first = arr[i] + L[j].first;
                L[i].second = j;
            }
        }
    }
 
    int maxi = INT_MIN, currIndex, track = 0;
 
    for (auto p : L) {
        if (p.first > maxi) {
            maxi = p.first;
            currIndex = track;
        }
        track++;
    }
 
    // Stores the final Subsequence
    vector<int> result;
 
    // Index of previous element
    // used to construct the Subsequence
    int prevoiusIndex;
 
    while (currIndex >= 0) {
        result.push_back(arr[currIndex]);
        prevoiusIndex = L[currIndex].second;
 
        if (currIndex == prevoiusIndex)
            break;
 
        currIndex = prevoiusIndex;
    }
 
    for (int i = result.size() - 1; i >= 0; i--)
        cout << result[i] << " ";
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 101, 2, 3, 100, 4, 5 };
    int n = arr.size();
 
    // Function call
    constructMaxSumIS(arr, n);
 
    return 0;
}

chevron_right


Output

1 2 3 100 

Time Complexity: O(N2)
Space Complexity: O(N)

This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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.




My Personal Notes arrow_drop_up