Problem · Array

Maximum Subarray Sum with Length at Most K

Learn this problem
HardOracle logoOracleFULLTIMEONSITE INTERVIEW

Problem 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) → long

Examples

Example 1

nums = [-2,3,-1,5,-6]k = 3return = 7

The length-three subarray [3, -1, 5] has sum 7, which is maximal.

Example 2

nums = [-5,-2,-7]k = 2return = -2

The subarray must be non-empty, so the best choice is the single value -2.

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • 1 <= k <= nums.length
  • -10^9 <= nums[i] <= 10^9
  • The result fits in a signed 64-bit integer.

More Oracle problems

drafts saved locally
public long maxSubarrayAtMostK(int[] nums, int k) {
    // Write your code here.
}
nums[-2,3,-1,5,-6]
k3
expected7
checking account