Maximum Sum Subarray of Size K

25 min · maxSumSubarrayK()
easy

A delivery team tracks how many orders arrive each hour. One busy stretch matters more than the whole day: which run of exactly k hours has the largest total?

Given an integer array nums and an integer k, return the largest sum among all contiguous subarrays — groups of neighboring elements with no gaps — whose length is exactly k.

A few ground rules:

  • The chosen group must contain exactly k values. You can't skip or reorder values.
  • Values may be negative. If every possible sum is negative, return the least negative one rather than 0.
  • A valid answer can be larger than a signed 32-bit integer, so keep the running sum in the signature's 64-bit long result type.

Constraints

  • 1 <= k <= nums.length <= 100_000
  • -100_000 <= nums[i] <= 100_000

Hints

Write the honest version first

Start at every possible index and add the next k values. It works, but notice how often neighboring windows add the same values again.

Compare neighboring windows

When a length-k window moves one position right, exactly one value leaves and one value enters. Everything between them stays in the sum.

Keep one running total

Add the first k values once. For each later position right, add nums[right], subtract nums[right - k], and update the best sum.

Follow-up

If the values arrived as a stream, could you still find the answer in one pass? What is the smallest amount of recent data you'd need to remember?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  1,
  5,
  1,
  3,
  2
]
k = 3
Expected
9
Why
the window [5, 1, 3] has the largest sum: 9

Example 2

ready
Input
nums = [
  -8,
  -3,
  -6,
  -2,
  -5,
  -4
]
k = 2
Expected
-7
Why
all windows are negative; [-2, -5] is best at -7

Example 3

ready
Input
nums = [
  4,
  -1,
  2,
  10
]
k = 1
Expected
10
Why
with k = 1, the largest individual value wins

Example 4

ready
Input
nums = [
  5,
  -2,
  3,
  4
]
k = 4
Expected
10
Why
when k equals the array length, the whole array is the only window

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

4 cases are queued.

Run: visible + custom · Submit: full suite