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