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
- 1 ≤ k ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴ (negatives allowed)
- Summing each window from scratch costs O(n·k); aim for O(n)
Edge cases to test
- k equals n (the whole array)
- All negative values
- k = 1
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 bestC++
#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
- Best Time to Buy and Sell Stock (Easy)
- Minimum Size Subarray Sum (Medium)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)
- Subarrays with K Different Integers (Hard)