1
+ package patterns .java ;
2
+
3
+ import java .util .HashSet ;
4
+
5
+ public 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 ));
63
+ maxLength = Math .max (maxLength , right - left + 1 );
64
+ }
65
+ return maxLength ;
66
+ }
67
+
68
+ public int lengthOfLongestSubstringSlidingWindowFrequencyArray (String s ) {
69
+ int n = s .length ();
70
+ int [] freq = new int [128 ]; // ASCII character frequency array
71
+ int maxLength = 0 ;
72
+ int left = 0 ;
73
+
74
+ // Expand window by moving 'right'
75
+ for (int right = 0 ; right < n ; right ++) {
76
+ char currentChar = s .charAt (right );
77
+ freq [currentChar ]++; // Increase frequency of the current character
78
+
79
+ // If there is a duplicate, shrink the window from the left
80
+ while (freq [currentChar ] > 1 ) {
81
+ freq [s .charAt (left )]--; // Remove character at left pointer
82
+ left ++; // Shrink window
83
+ }
84
+
85
+ // Update maximum window size
86
+ maxLength = Math .max (maxLength , right - left + 1 );
87
+ }
88
+ return maxLength ;
89
+ }
90
+ }
0 commit comments