Skip to content

1425. Constrained Subsequence Sum 👍

  • Time: $O(n)$
  • Space: $O(k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int constrainedSubsetSum(vector<int>& nums, int k) {
    // dp[i] := the maximum the sum of non-empty subsequences in nums[0..i]
    vector<int> dp(nums.size());
    // dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0
    // in decreasing order.
    deque<int> dq;

    for (int i = 0; i < nums.size(); ++i) {
      if (dq.empty())
        dp[i] = nums[i];
      else
        dp[i] = max(dq.front(), 0) + nums[i];
      while (!dq.empty() && dq.back() < dp[i])
        dq.pop_back();
      dq.push_back(dp[i]);
      if (i >= k && dp[i - k] == dq.front())
        dq.pop_front();
    }

    return ranges::max(dp);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int constrainedSubsetSum(int[] nums, int k) {
    // dp[i] := the maximum the sum of non-empty subsequences in nums[0..i]
    int[] dp = new int[nums.length];
    // dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0
    // in decreasing order.
    Deque<Integer> dq = new ArrayDeque<>();

    for (int i = 0; i < nums.length; ++i) {
      if (dq.isEmpty())
        dp[i] = nums[i];
      else
        dp[i] = Math.max(dq.peekFirst(), 0) + nums[i];
      while (!dq.isEmpty() && dq.peekLast() < dp[i])
        dq.pollLast();
      dq.offerLast(dp[i]);
      if (i >= k && dp[i - k] == dq.peekFirst())
        dq.pollFirst();
    }

    return Arrays.stream(dp).max().getAsInt();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
    # dp[i] := the maximum the sum of non-empty subsequences in nums[0..i]
    dp = [0] * len(nums)
    # dq stores dp[i - k], dp[i - k + 1], ..., dp[i - 1] whose values are > 0
    # in decreasing order.
    dq = collections.deque()

    for i, num in enumerate(nums):
      if dq:
        dp[i] = max(dq[0], 0) + num
      else:
        dp[i] = num
      while dq and dq[-1] < dp[i]:
        dq.pop()
      dq.append(dp[i])
      if i >= k and dp[i - k] == dq[0]:
        dq.popleft()

    return max(dp)