Maximum Sum Subarray of Size K in Java: Explanation & Practice
Find maximum sum of any contiguous subarray of size k
Problem summary
Given an array and integer k, find the maximum sum of any contiguous subarray of size k. Use sliding window for O(n) solution.
Starter code
public class Main {
public static void main(String[] args) {
int[] nums = {2, 1, 5, 1, 3, 2};
int k = 3;
// Sliding window: maintain sum of k elements
// Slide by adding new element and removing old
// Print: Max sum: 9
}
}Expected output and test cases
- [2,1,5,1,3,2], k=3 → 5+1+3
Max sum: 9
- [2,3,4,1,5], k=2 → 3+4
Max sum: 7
- [1,2,3,4,5], k=5 → all
Max sum: 15
Hints
- First compute sum of first k elements
- Then slide: add nums[i], subtract nums[i-k]
- Track maximum sum seen
- This avoids recomputing sum from scratch each time
Related Data Structures & Algorithms exercises
- Practice Three Sum in Java
- Practice Valid Palindrome in Java
- Practice Longest Substring with K Distinct Characters in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler