Constrained Subsequence Sum

Hard Topics Company Tags

Choose a nonempty subsequence of nums to maximize its sum. For every pair of consecutive chosen elements, the difference between their original indices must be at most k. Return the largest achievable sum. A subsequence preserves the original order and may skip elements.

Example 1:

Input: nums = [4,-8,5,-1,6]
k = 2

Output: 15

Explanation: Choose the values 4, 5, and 6 at indices 0, 2, and 4. Each index gap is 2 and the sum is 15. All positive values are included, so no larger sum is possible.

Example 2:

Input: nums = [-5,-2,-7]
k = 3

Output: -2

Explanation: A nonempty subsequence is required. Choosing only -2 gives the largest sum; adding any other value would decrease it.

Example 3:

Input: nums = [5,-9,6]
k = 1

Output: 6

Explanation: With k = 1, chosen indices must be consecutive. The best choice is the single value 6, because connecting 5 to 6 requires including -9.

Constraints:

  • 1 <= nums.length <= 100000
  • -10000 <= nums[i] <= 10000
  • 1 <= k <= nums.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.