Skip to content

Instantly share code, notes, and snippets.

@bittib
Created May 13, 2013 08:27
Show Gist options
  • Save bittib/5566920 to your computer and use it in GitHub Desktop.
Save bittib/5566920 to your computer and use it in GitHub Desktop.
find max of K size sliding window from a stream
/**
* Time Complexity: O(n)
*/
public int[] minOfSlidingWindow(int[] A, int k){
int n = A.length;
int[] B = new int[n - k + 1];
int[] queue = new int[n];
int head = 0, tail = 0;
for (int i=0; i<n; i++){
while (head < tail && A[i] <= A[queue[tail-1]])
tail--;
queue[tail++] = i;
if (i >= k-1){
while (head < tail && i - queue[head] >= k)
head++;
B[i-k+1] = A[queue[head]];
}
}
return B;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment