forked from javadev/LeetCode-in-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Solution.kt
34 lines (31 loc) · 978 Bytes
/
Solution.kt
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
package g0201_0300.s0239_sliding_window_maximum
// #Hard #Top_100_Liked_Questions #Array #Heap_Priority_Queue #Sliding_Window #Queue
// #Monotonic_Queue #Udemy_Arrays #Big_O_Time_O(n*k)_Space_O(n+k)
// #2022_09_10_Time_1059_ms_(86.14%)_Space_113.7_MB_(65.35%)
import java.util.LinkedList
class Solution {
fun maxSlidingWindow(nums: IntArray, k: Int): IntArray {
val n = nums.size
val res = IntArray(n - k + 1)
var x = 0
val dq = LinkedList<Int>()
var i = 0
var j = 0
while (j < nums.size) {
while (dq.isNotEmpty() && dq.peekLast() < nums[j]) {
dq.pollLast()
}
dq.addLast(nums[j])
if (j - i + 1 == k) {
res[x] = dq.peekFirst()
++x
if (dq.peekFirst() == nums[i]) {
dq.pollFirst()
}
++i
}
++j
}
return res
}
}