Chaturmind
LearnDSASystem DesignBlogPremium
Sign inGet started
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML

Company

  • Blog
  • Premium
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Two Pointers & Sliding Window›Maximum Sum Subarray of Size K
EasyTwo Pointers & Sliding Window

Maximum Sum Subarray of Size K

sliding-windowarray

Problem

Given an array of positive integers arr and a positive integer k, find the maximum sum of any contiguous subarray of size exactly k.

Examples

Example 1

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

Output: 9

Explanation: The subarray [5,1,3] has the maximum sum of 9.

Example 2

Input: arr = [2,3,4,1,5], k = 2

Output: 7

Explanation: The subarray [3,4] has the maximum sum of 7.

Constraints

  • •1 <= k <= arr.length <= 10^5
  • •1 <= arr[i] <= 10^4

Hints

Hint 1

The naive approach recomputes the sum of each window from scratch — O(n*k). What's being recomputed unnecessarily?

Hint 2

A fixed-size window sliding by one position only changes by two elements: one leaves, one enters.

Hint 3

Maintain a running sum and update it incrementally instead of resumming the whole window each time.

Solutions

public int maxSumSubarray(int[] arr, int k) {
    int windowSum = 0;
    for (int i = 0; i < k; i++) windowSum += arr[i];
    int maxSum = windowSum;
    for (int right = k; right < arr.length; right++) {
        windowSum += arr[right] - arr[right - k]; // add new element, remove element leaving the window
        maxSum = Math.max(maxSum, windowSum);
    }
    return maxSum;
}
Java

Time: O(n) · Space: O(1)