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
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
java
@GetMapping("/files/{id}") public ResponseEntity<StreamingResponseBody> download( @PathVariable String id, @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) throws IOException {
HTTP range requests in Spring
http-range
streaming
file-io
Advanced
10 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.