-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlidingWindow.java
More file actions
81 lines (59 loc) · 2.16 KB
/
SlidingWindow.java
File metadata and controls
81 lines (59 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
⭐ Pattern 1 — Fixed Window (foundation)
👉 Window size always = k
👉 Add right, remove left
✅ Must solve
Maximum sum subarray of size k
First negative number in window k
Count distinct elements in window k
Average of subarray size k
Maximum number of vowels in substring k
1)class Solution {
public int maxSubarraySum(int[] arr, int k) {
//ok to solve optimal i can us slidinwinodw tehique
int n = arr.length;
int maxSum = Integer.MIN_VALUE;
int currSum =0;
int left =0;
for(int right=0;right<n;right++){
currSum +=arr[right];
if(right-left+1==k){
maxSum = Math.max(maxSum,currSum);
//remove left
currSum -=arr[left];
left++;
}
}
return maxSum;
}
2)class Solution {
static List<Integer> firstNegInt(int nums[], int k) {
// write code here
int n = nums.length;
List<Integer>res = new ArrayList<>();
Deque<Integer>dq = new ArrayDeque<>();
//see first i need to maintian window and add negtive into dq
//then check if its empty we add list 0if not we add negtive and we laso ceh
//when window moves we need to check if netive is there we need or update dq to get next negtives
int left =0;
for(int right=0;right<n;right++){
if(nums[right]<0){
dq.add(nums[right]);
}
//whenw e meetwindow size
if(right-left+1==k){
if(dq.isEmpty()){
res.add(0);
}else{
res.add(dq.peek());
}
//and cehck left values update
if(nums[left]<0){
dq.poll();
}
left++;
}
}
return res;
}
}
}