-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlidingWindowMaximum.py
47 lines (45 loc) · 1.38 KB
/
SlidingWindowMaximum.py
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
44
45
46
47
# https://www.interviewbit.com/problems/sliding-window-maximum/
def fillNextNotSmallers(A, arr):
stack = []
i = 0
while i < len(A):
cur = A[i]
if not stack:
stack.append((i, cur))
else:
while True:
if not stack:
stack.append((i, cur))
break
prev = stack.pop()
if cur >= prev[1]:
arr[prev[0]] = i
else:
stack.append(prev)
stack.append((i, cur))
break
i += 1
class Solution:
# @param A : tuple of integers
# @param B : integer
# @return a list of integers
def slidingMaximum(self, A, B):
result = [0] * (len(A) - B + 1)
nextNotSmallers = [-1] * len(A)
fillNextNotSmallers(A, nextNotSmallers)
for i in range(len(result)):
if nextNotSmallers[i] == -1:
result[i] = A[i]
else:
prevJ = i
j = i
while True:
if j == -1:
result[i] = A[prevJ]
break
elif nextNotSmallers[j] >= i + B:
result[i] = A[j]
break
prevJ = j
j = nextNotSmallers[j]
return result