-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlast_n_high.py
66 lines (52 loc) · 1.38 KB
/
last_n_high.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import collections
import time
import sys
class LastNHigh:
def __init__(self, n):
self._place = 0
self._n = n
self._deque = collections.deque(maxlen=n)
def insert(self, new_value):
if self._deque and self._deque[0][0] + self._n <= self._place:
self._deque.popleft()
while self._deque:
(place, value) = self._deque[-1]
if value <= new_value:
self._deque.pop()
else:
break
self._deque.append((self._place, new_value,))
self._place = self._place + 1
assert self._deque
def last_n_high(self):
if not self._deque:
return sys.maxint
return self._deque[0][1]
def test_basic():
last_n_high = LastNHigh(5)
for x in range(1,6):
last_n_high.insert(x)
assert last_n_high.last_n_high() == x
for x in range(1,5):
last_n_high.insert(5 - x)
assert last_n_high.last_n_high() == 5
for x in range(1,5):
last_n_high.insert(1)
assert last_n_high.last_n_high() == (5 - x)
def test_worst_case():
start = time.clock()
n = 10000
last_n_high = LastNHigh(n)
for x in xrange(n, 0, -1):
sign = 1 - (x % 2) * 2
last_n_high.insert(sign * x)
for x in xrange(n, 0, -1):
if x % 2 == 1:
x = x - 1
assert last_n_high.last_n_high() == x
last_n_high.insert(0)
duration = time.clock() - start
print duration
if __name__ == '__main__':
test_basic()
test_worst_case()