Problem · Array
Maximum Subarray Sum with Length at Most K
Learn this problemProblem statement
Given an integer array nums and an integer k, return the maximum sum of a non-empty contiguous subarray whose length is at most k.
The array may contain negative values, so the answer may be negative.
Function
maxSubarrayAtMostK(nums: int[], k: int) → longExamples
Example 1
nums = [-2,3,-1,5,-6]k = 3return = 7The length-three subarray [3, -1, 5] has sum 7, which is maximal.
Example 2
nums = [-5,-2,-7]k = 2return = -2The subarray must be non-empty, so the best choice is the single value -2.
Constraints
1 <= nums.length <= 2 * 10^51 <= k <= nums.length-10^9 <= nums[i] <= 10^9- The result fits in a signed 64-bit integer.