Constrained Subsequence Sum

Hard

Description

Given an integer array nums and integer k, return the maximum sum of a non-empty subsequence where consecutive elements in the original array differ by at most k indices.

Examples

Input:nums = [10,2,-10,5,20], k = 2
Output:37
Explanation:

Take [10,2,5,20].

Input:nums = [-1,-2,-3], k = 1
Output:-1
Explanation:

Works with negative numbers.

Input:nums = [1, -5, 8, -3, 12, 6], k = 3
Output:26
Explanation:

The subsequence [1, 8, 12, 6] at indices [0, 2, 4, 5] skips negative values while keeping consecutive index gaps ≤ k=3.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!