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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Maintaining a running sum and updating it incrementally turns an O(n*k) brute force into a single O(n) pass.
- 2Validating arguments up front keeps the core loop simple and surfaces misuse clearly.
- 3Tracking the index where the best result occurs costs almost nothing and lets you return the window itself, not just its score.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/the-sliding-window-technique-in-java-explained-java-536c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.