Maximum Sum Subarray Size K
You are given an integer array nums and an integer k. Consider every contiguous subarray (window) of length k, compute its sum, and return the largest sum among all these windows.
This problem is a classic fixed-size sliding window. A brute-force method recalculates each window from scratch, which costs O(n*k). The sliding window idea reduces this to O(n): compute the first window sum once, then move the window one step at a time by adding the new right element and removing the left element that leaves the window.
If k is invalid (for example k <= 0 or k > nums.length), no valid window exists and the expected result is 0 in this challenge.
Example 1:
Input: nums = [2,1,5,1,3,2], k = 3
Output: 9
Explanation: The window sums are 8 ([2,1,5]), 7 ([1,5,1]), 9 ([5,1,3]), 6 ([1,3,2]). The maximum is 9.
Example 2:
Input: nums = [2,3,4,1,5], k = 2
Output: 7
Explanation: Window sums are 5, 7, 5, 6. Best answer is 7.
Example 3:
Input: nums = [1,1,1], k = 4
Output: 0
Explanation: No window of size 4 can be formed.
Constraints: 1 <= nums.length <= 10^5, -10^4 <= nums[i] <= 10^4
Algorithm Flow

Best Answers
class Solution {
public int maximum_sum_subarray_size_k(int[] nums, int k) {
int n = nums.length;
if (k <= 0 || k > n) return 0;
int window = 0;
for (int i = 0; i < k; i++) window += nums[i];
int best = window;
for (int i = k; i < n; i++) {
window += nums[i] - nums[i-k];
if (window > best) best = window;
}
return best;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
