Algo-Sim › Sliding Window

Maximum Sum Subarray of Size K

Easy · Sliding Window · step through it in Java, Python and C++ on your own input

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

Problem

Given an integer array nums and a window size k, consider every contiguous block of exactly k elements. Return the largest sum any of these blocks has.

Constraints

Edge cases to test

Follow-up questions

What if k is not fixed and you want the best sum of any length?
Kadane’s algorithm: keep the best sum ending here, O(n) time, O(1) space.
What if you want the maximum average of length at least k?
Binary search on the average and check with prefix sums whether some window of length ≥ k beats it: O(n log range) (LC 644).

Solution

Java

public int maxSumSubarray(int[] nums, int k) {
    int windowSum = 0, left = 0;
    int best = Integer.MIN_VALUE;
    for (int right = 0; right < nums.length; right++) {
        windowSum += nums[right];
        if (right - left + 1 == k) {
            best = Math.max(best, windowSum);
            windowSum -= nums[left];
            left++;
        }
    }
    return best;
}

Python

def max_sum_subarray(nums, k):
    window_sum, left = 0, 0
    best = float("-inf")
    for right in range(len(nums)):
        window_sum += nums[right]
        if right - left + 1 == k:
            best = max(best, window_sum)
            window_sum -= nums[left]
            left += 1
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxSumSubarray(vector<int> &nums, int k) {
        int windowSum = 0, left = 0;
        int best = INT_MIN;
        for (int right = 0; right < int(nums.size()); right++) {
            windowSum += nums[right];
            if (right - left + 1 == k) {
                best = std::max(best, windowSum);
                windowSum -= nums[left];
                left++;
            }
        }
        return best;
    }
};

More Sliding Window problems