Skip to content
Merged
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
17 changes: 9 additions & 8 deletions java/Stacks/MaximumsOfSlidingWindow.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import java.util.Stack;
import java.util.ArrayDeque;
import java.util.Deque;

public class MaximumsOfSlidingWindow {
public int[] maximumsOfSlidingWindow(int[] nums, int k) {
int[] res = new int[nums.length - k + 1];
Stack<int[]> dq = new Stack<>();
Deque<int[]> dq = new ArrayDeque<>();
int left, right;
left = right = 0;
while (right < nums.length) {
// 1) Ensure the values of the deque maintain a monotonic decreasing order
// by removing candidates <= the current candidate.
while (!dq.isEmpty() && dq.peek()[0] <= nums[right]) {
dq.pop();
while (!dq.isEmpty() && dq.peekLast()[0] <= nums[right]) {
dq.pollLast();
}
// 2) Add the current candidate.
dq.push(new int[]{nums[right], right});
dq.offerLast(new int[]{nums[right], right});
// If the window is of length 'k', record the maximum of the window.
if (right - left + 1 == k) {
// 3) Remove values whose indexes occur outside the window.
if (!dq.isEmpty() && dq.firstElement()[1] < left) {
dq.remove(0);
if (!dq.isEmpty() && dq.peekFirst()[1] < left) {
dq.pollFirst();
}
// The maximum value of this window is the leftmost value in the
// deque.
res[left] = dq.firstElement()[0];
res[left] = dq.peekFirst()[0];
// Slide the window by advancing both 'left' and 'right'. The right
// pointer always gets advanced so we just need to advance 'left'.
left++;
Expand Down