Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array such that the intgers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5}, then output should be 106 (1 + 2 + 3 + 100), if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and if the input array is {10, 5, 4, 3}, then output should be 10

Solution
This problem is a variation of standard Longest Increasing Subsequence (LIS) problem. We need a slight change in the Dynamic Programming solution of LIS problem. All we need to change is to use sum as a criteria instead of length of increasing subsequence.

Following are C++ implementations for Dynamic Programming solution of the problem.

[pastacode lang=”cpp” manual=”%2F*%20Dynamic%20Programming%20implementation%20of%20Maximum%20Sum%20Increasing%0ASubsequence%20(MSIS)%20problem%20*%2F%0A%23include%3Cstdio.h%3E%0A%20%0A%2F*%20maxSumIS()%20returns%20the%20maximum%20sum%20of%20increasing%20subsequence%0A%20%20%20%20in%20arr%5B%5D%20of%20size%20n%20*%2F%0Aint%20maxSumIS(%20int%20arr%5B%5D%2C%20int%20n%20)%0A%7B%0A%20%20%20%20int%20i%2C%20j%2C%20max%20%3D%200%3B%0A%20%20%20%20int%20msis%5Bn%5D%3B%0A%20%0A%20%20%20%20%2F*%20Initialize%20msis%20values%20for%20all%20indexes%20*%2F%0A%20%20%20%20for%20(%20i%20%3D%200%3B%20i%20%3C%20n%3B%20i%2B%2B%20)%0A%20%20%20%20%20%20%20%20msis%5Bi%5D%20%3D%20arr%5Bi%5D%3B%0A%20%0A%20%20%20%20%2F*%20Compute%20maximum%20sum%20values%20in%20bottom%20up%20manner%20*%2F%0A%20%20%20%20for%20(%20i%20%3D%201%3B%20i%20%3C%20n%3B%20i%2B%2B%20)%0A%20%20%20%20%20%20%20%20for%20(%20j%20%3D%200%3B%20j%20%3C%20i%3B%20j%2B%2B%20)%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20(%20arr%5Bi%5D%20%3E%20arr%5Bj%5D%20%26%26%20msis%5Bi%5D%20%3C%20msis%5Bj%5D%20%2B%20arr%5Bi%5D)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20msis%5Bi%5D%20%3D%20msis%5Bj%5D%20%2B%20arr%5Bi%5D%3B%0A%20%0A%20%20%20%20%2F*%20Pick%20maximum%20of%20all%20msis%20values%20*%2F%0A%20%20%20%20for%20(%20i%20%3D%200%3B%20i%20%3C%20n%3B%20i%2B%2B%20)%0A%20%20%20%20%20%20%20%20if%20(%20max%20%3C%20msis%5Bi%5D%20)%0A%20%20%20%20%20%20%20%20%20%20%20%20max%20%3D%20msis%5Bi%5D%3B%0A%20%0A%20%20%20%20return%20max%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20function%20*%2F%0Aint%20main()%0A%7B%0A%20%20%20%20int%20arr%5B%5D%20%3D%20%7B1%2C%20101%2C%202%2C%203%2C%20100%2C%204%2C%205%7D%3B%0A%20%20%20%20int%20n%20%3D%20sizeof(arr)%2Fsizeof(arr%5B0%5D)%3B%0A%20%20%20%20printf(%22Sum%20of%20maximum%20sum%20increasing%20subsequence%20is%20%25d%5Cn%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20maxSumIS(%20arr%2C%20n%20)%20)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”C++” highlight=”” provider=”manual”/]

Output:

Sum of maximum sum increasing subsequence is 106

Time Complexity: O(n^2)

[ad type=”banner”]