Maximum Sum Increasing Subsequence

Pattern: LIS family

medium

Like LIS, but store the largest sum instead of the longest length: sum[i] = a[i] + the best sum[j] over earlier smaller values.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the largest sum of a strictly increasing subsequence of arr.

Think first

  • What does each index store now?
  • Which earlier indexes may be extended?
  • Is the longest run the best sum?

Hints

    Brute force, and why it fails

    Try every subsequence: 2ⁿ.

    The key insight

    The LIS recurrence works for any additive score, not just length.

    Dry run

    [1, 101, 2, 3, 100]. sum: 1, 102, 3, 6.

    Step 1 of 2

    The plan

    sum[i] = a[i] + max(sum[j] for j < i with a[j] < a[i], default 0)
    return max(sum)
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    Every pair.

    Edge cases

    • One value.
    • Decreasing array: the largest value.
    • Equal values.
    I've built my logic, show the code

    Java

    class Solution {
        public int maxSumIS(int[] arr) {
            int n = arr.length, best = 0;
            int[] sum = new int[n];                 // sum[i]: the largest sum of an increasing run ending at i
            for (int i = 0; i < n; i++) {
                sum[i] = arr[i];
                for (int j = 0; j < i; j++) if (arr[j] < arr[i]) sum[i] = Math.max(sum[i], sum[j] + arr[i]);   // LIS with sums
                best = Math.max(best, sum[i]);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int maxSumIS(vector<int>& arr) {
            int n = static_cast<int>(arr.size()), best = 0;
            vector<int> sum(n);                     // sum[i]: the largest sum of an increasing run ending at i
            for (int i = 0; i < n; i++) {
                sum[i] = arr[i];
                for (int j = 0; j < i; j++) if (arr[j] < arr[i]) sum[i] = max(sum[i], sum[j] + arr[i]);   // LIS with sums
                best = max(best, sum[i]);
            }
            return best;
        }
    };

    Python

    class Solution:
        def maxSumIS(self, arr: list[int]) -> int:
            best = []                               # best[i]: the largest sum of an increasing run ending at i
            for i, x in enumerate(arr):
                best.append(x + max((best[j] for j in range(i) if arr[j] < x), default=0))   # LIS with sums
            return max(best)

    Common mistakes

    • Returning the sum of the longest run.
    • Allowing equal values.

    Similar problems