-
Notifications
You must be signed in to change notification settings - Fork 1
/
SlidingWindowMaximum.java
43 lines (37 loc) · 1.06 KB
/
SlidingWindowMaximum.java
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
package com.smlnskgmail.jaman.leetcodejava.hard;
import java.util.Deque;
import java.util.LinkedList;
// https://leetcode.com/problems/sliding-window-maximum/
public class SlidingWindowMaximum {
private final int[] nums;
private final int k;
public SlidingWindowMaximum(int[] nums, int k) {
this.nums = nums;
this.k = k;
}
public int[] solution() {
int[] result = new int[nums.length - k + 1];
int p = 0;
int i = 0;
int j = 0;
Deque<Integer> deq = new LinkedList<>();
while (j < nums.length) {
while (!deq.isEmpty() && nums[j] > deq.peekLast()) {
deq.removeLast();
}
deq.addLast(nums[j]);
int size = j - i + 1;
if (size < k) {
j++;
} else {
result[p++] = deq.peekFirst();
if (deq.peekFirst() == nums[i]) {
deq.removeFirst();
}
i++;
j++;
}
}
return result;
}
}