DevPath

← All problems

Maximum Sum Subarray of Size K

Easy arrays · sliding-window

Description

Return the largest sum of any contiguous subarray of exactly k elements.

Constraints

1 <= k <= n <= 100000

Examples

Input: nums = [2,1,5,1,3,2], k = 3

Output: 9

[5,1,3]

Hints (1)
  • Slide the window by adding the entering element and removing the leaving one.

Solutions

Fixed-size sliding window. · Time O(n) · Space O(1)

func maxSumSizeK(nums []int, k int) int {
    sum := 0
    for i := 0; i < k; i++ {
        sum += nums[i]
    }
    best := sum
    for i := k; i < len(nums); i++ {
        sum += nums[i] - nums[i-k]
        if sum > best {
            best = sum
        }
    }
    return best
}

Create a free account to submit solutions, track progress and save problems.

Create account