ntree.aiConstrained Subsequence Sum
Constrained Subsequence Sum
hardsolvedattempted
Given an array of integers nums and an integer k, return the largest sum of a non-empty subsequence of nums in which every two consecutive picked elements are at most k indexes apart.
A subsequence keeps the elements in their original order, but can skip some of them.
Example 1:
Input: nums = [10, 2, -10, 5, 20], k = 2
Output: 37
Explanation: [10, 2, 5, 20] adds up to 37, and no two picked elements are more than 2 indexes apart.
Example 2:
Input: nums = [-1, -2, -3], k = 1
Output: -1
Explanation: the subsequence must be non-empty, so the best is the single element -1.
Example 3:
Input: nums = [10, -2, -10, -5, 20], k = 2
Output: 23
Explanation: [10, -2, -5, 20] adds up to 23. Skipping -2 and -5 would leave a gap of more than 2.
Constraints:
1 <= k <= length of nums <= 10^5-10^4 <= nums[i] <= 10^4
def constrainedSubsetSum(nums: list[int], k: int) -> int: pass Press Visualise to step through your code.