Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added SlidingWindow in java #106

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Java/SlidingWindow.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.Deque;
import java.util.LinkedList;
public class Slidingwindow {








public static void main(String[] args) {
Solution solution= new Solution();
int a[]= {4,3,1,2,5,3,4,7,1,9};
int ans[]= solution.maxSlidingWindow(a, 4);

for(int x:ans) {
System.out.print(x+" ");
}
}
static class Solution {
public int[] maxSlidingWindow(int[] a, int k) {
int n= a.length;
Deque<Integer>dq=new LinkedList<>();
int ans[]=new int[n-k+1];


int i=0;
for(;i<k;i++) {
while(!dq.isEmpty()&& a[dq.peekLast()]<=a[i]) {
dq.removeLast();
}
dq.addLast(i);
}
for(;i<n;i++) {

ans[i-k]=a[dq.peekFirst()];

while(!dq.isEmpty() && dq.peekFirst()<=i-k) {
dq.removeFirst();

}

while(!dq.isEmpty()&& a[dq.peekLast()]<=a[i]) {
dq.removeLast();
}
dq.addLast(i);
}
ans[i-k]=a[ dq.peekFirst()];
return ans;





}

}

}