Find the maximum sum of increasing sub-sequence

Description:

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.

Example:

input:
{1, 101, 2, 3, 100, 4, 5}
output:  
106 (1 + 2 + 3 + 100); 
Input:{3, 4, 5, 10} 
output:
22 (3 + 4 + 5 + 10);
input: 
{10, 5, 4, 3}
output:
10

解题方法:

this is the upgrade version of longest increasing subsequence
we still need a helper array to save the position of each elements in its increasing subsequence
the result = max(sum[i + 1]); which 0 <= i < nums.size();
for example:
input (1, 101, 2, 3, 100, 4, 5)

giving 1
DP: 1
Sum: 0, 1
***
giving 101
DP: 1, 101
Sum: 0, 1, 102
***
giving 2
DP: 1, 2
Sum: 0, 1, 3
***
giving 3
DP: 1, 2, 3
Sum: 0, 1, 3, 6
*** 
giving 100
DP: 1, 2, 3, 100
Sum: 0, 1, 3, 6, 106
.
.
.

Time Complexity:

O(nlogn) just like LIS

完整代码:

int binarySearch(vector<int>& nums, int n) {
    int len = nums.size();
    if(!len || n <= nums[0])
        return 0;
    if(n > nums[len - 1])
        return len;
    int start = 0, end = len - 1;
    while(start + 1 < end) {
        int mid = start + (end - start) / 2;
        if(nums[mid] == n)
            return mid;
        else if(nums[mid] > n)
            end  = mid;
        else 
            start = mid;
    }
    if(nums[start] >= n)
        return start;
    return end;
}
int maxSumOfLIS(vector<int>& nums) {
    int len = nums.size();
    if(!len)
        return 0;
    vector<int> DP;
    vector<int> sum(1, 0);
    int result = 0;
    for(int i: nums) {
        int index = binarySearch(DP, i);
        if(index == DP.size())
            DP.push_back(i);
        else 
            DP[index] = i;
        if(index >= sum.size() - 1)
            sum.push_back(sum.back() + i);
        else
            sum[index + 1] = sum[index] + i;
        result = max(sum[index + 1], result);
    }
    return result;
}
    原文作者:黑山老水
    原文地址: https://www.jianshu.com/p/de8534622289
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞