Constrained Subsequence Sum
Description
Given an integer array nums
and an integer k
, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i]
and nums[j]
, where i < j
, the condition j - i <= k
is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2 Output: 37 Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1 Output: -1 Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2 Output: 23 Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
Solution(javascript)
// /** 1: DP time limited exceed
// * @param {number[]} nums
// * @param {number} k
// * @return {number}
// */
// const constrainedSubsetSum = function (nums, k) {
// const memo = {}
// const sumMemo = {}
// const sum = (index) => {
// if (sumMemo[index] !== undefined) {
// return sumMemo[index]
// }
// let result = 0
// for (let i = index; i < nums.length; i++) {
// if (nums[i] > 0) {
// result += nums[i]
// }
// }
// sumMemo[index] = result
// return result
// }
// const aux = (index, currentK) => {
// const key = `${index}-${currentK}`
// if (memo[key] !== undefined) {
// return memo[key]
// }
// if (index > nums.length - 1 || currentK <= 0) {
// return 0
// }
// if (currentK >= nums.length - index) {
// memo[key] = sum(index)
// } else {
// memo[key] = Math.max(
// nums[index] + aux(index + 1, k),
// aux(index + 1, currentK - 1),
// )
// }
// return memo[key]
// }
// let max = -Infinity
// for (let i = 0; i < nums.length; i++) {
// max = Math.max(nums[i] + aux(i + 1, k), max)
// }
// return max
// }
/** 2: Sliding window
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
const constrainedSubsetSum = function (nums, k) {
const dp = [[0, nums[0]]]
let max = nums[0]
for (let i = 1; i < nums.length; i++) {
const [index, prevMax] = dp[0]
if (index === i - k) {
dp.shift()
}
const currentMax = Math.max(prevMax, 0) + nums[i]
max = Math.max(max, currentMax)
while (dp.length > 0 && dp[dp.length - 1][1] < currentMax) {
dp.pop()
}
dp.push([i, currentMax])
}
return max
}