MCPcopy Create free account
hub / github.com/ashishps1/awesome-leetcode-resources / SlidingWindow

Class SlidingWindow

patterns/java/SlidingWindow.java:5–90  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3import java.util.HashSet;
4
5public class SlidingWindow {
6 public double findMaxAverageBruteForce(int[] nums, int k) {
7 int n = nums.length;
8 double maxAvg = Integer.MIN_VALUE;
9
10 // Iterate through all possible subarrays of length k
11 for (int i = 0; i <= n - k; i++) {
12 int sum = 0;
13
14 // Calculate sum of subarray starting at index i
15 for (int j = i; j < i + k; j++) {
16 sum += nums[j];
17 }
18
19 // Compute average and update maxAvg
20 maxAvg = Math.max(maxAvg, (double) sum / k);
21 }
22 return maxAvg;
23 }
24
25 public double findMaxAverageSlidingWindow(int[] nums, int k) {
26 int n = nums.length;
27
28 // Compute the sum of the first 'k' elements
29 int sum = 0;
30 for (int i = 0; i < k; i++) {
31 sum += nums[i];
32 }
33
34 // Initialize maxSum as the sum of the first window
35 int maxSum = sum;
36
37 // Slide the window across the array
38 for (int i = k; i < n; i++) {
39 sum += nums[i]; // Add new element entering window
40 sum -= nums[i - k]; // Remove element leaving window
41 maxSum = Math.max(maxSum, sum); // Update maxSum
42 }
43
44 // Return maximum average
45 return (double) maxSum / k;
46 }
47
48 public int lengthOfLongestSubstringSlidingWindow(String s) {
49 int n = s.length();
50 HashSet<Character> seen = new HashSet<>(); // Store characters in the current window
51 int maxLength = 0;
52 int left = 0;
53
54 // Expand window by moving 'right'
55 for (int right = 0; right < n; right++) {
56 // If a duplicate is found, shrink the window from the left
57 while (seen.contains(s.charAt(right))) {
58 seen.remove(s.charAt(left));
59 left++;
60 }
61 // Add current character to window and update max length
62 seen.add(s.charAt(right));

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected