java 43 lines · 8 steps

The sliding window technique in Java

Find the best fixed-length subarray in one pass by adding and removing one element at a time instead of resumming.

Explained by highlit
1import java.util.Arrays;
2 
3public class SlidingWindow {
4 // Returns the maximum sum of any contiguous subarray of length k.
5 public static long maxSubarraySum(int[] nums, int k) {
6 if (nums == null || k <= 0 || k > nums.length) {
7 throw new IllegalArgumentException(
8 "k must be between 1 and " + (nums == null ? 0 : nums.length));
9 }
10 
11 long windowSum = 0;
12 for (int i = 0; i < k; i++) {
13 windowSum += nums[i];
14 }
15 
16 long maxSum = windowSum;
17 for (int end = k; end < nums.length; end++) {
18 // Slide the window: add the entering element, drop the leaving one.
19 windowSum += nums[end] - nums[end - k];
20 maxSum = Math.max(maxSum, windowSum);
21 }
22 return maxSum;
23 }
24 
25 // Variant: also report where the best window starts.
26 public static int[] maxSubarrayRange(int[] nums, int k) {
27 long windowSum = 0;
28 for (int i = 0; i < k; i++) {
29 windowSum += nums[i];
30 }
31 
32 long maxSum = windowSum;
33 int bestStart = 0;
34 for (int end = k; end < nums.length; end++) {
35 windowSum += nums[end] - nums[end - k];
36 if (windowSum > maxSum) {
37 maxSum = windowSum;
38 bestStart = end - k + 1;
39 }
40 }
41 return Arrays.copyOfRange(nums, bestStart, bestStart + k);
42 }
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Maintaining a running sum and updating it incrementally turns an O(n*k) brute force into a single O(n) pass.
  2. 2Validating arguments up front keeps the core loop simple and surfaces misuse clearly.
  3. 3Tracking the index where the best result occurs costs almost nothing and lets you return the window itself, not just its score.

Related explainers

Share this explainer

Here's the card — post it anywhere.

The sliding window technique in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code