I/P: { 2, 9, 3, 8, 1, 7, 12, 6, 14, 4, 32, 0, 7, 19, 8, 12, 6}
O/P: 9 9 8 12 12 14 14 32 32 32 32 19 19 19
package pep.Day27;
import java.util.Stack;
public class Sliding_window_max {
public static void main(String[] args) {
int[] arr = {2, 9, 3, 8, 1, 7, 12, 6, 14, 4, 32, 0, 7, 19, 8, 12, 6};
int n = arr.length;
int k = 4;
int[] ng = nextGreaterToRight(arr);
int jumper = 0;
for (int i = 0; i <= n - k; i++) {
if (jumper < i) jumper = i;
while (ng[jumper] < i + k) jumper = ng[jumper];
System.out.println(arr[jumper]);
}
}
public static int[] nextGreaterToRight(int[] arr) {
int n = arr.length;
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) stack.pop();
ans[i] = stack.isEmpty() ? n : stack.peek();
stack.push(i);
}
return ans;
}
}
No comments:
Post a Comment