forked from learning-zone/python-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzig_zag.py
149 lines (98 loc) · 2.71 KB
/
zig_zag.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
"""A sequence of integers is called a zigzag sequence if each of its elements is either strictly less than both neighbors or strictly greater than both neighbors. For example, the sequence 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2 and 3 8 6 4 5 aren't.
For a given array of integers return the length of its longest contiguous sub-array that is a zigzag sequence.
Example
For a = [9, 8, 8, 5, 3, 5, 3, 2, 8, 6], the output should be
zigzag(a) = 4.
The longest zigzag sub-arrays are [5, 3, 5, 3] and [3, 2, 8, 6] and they both have length 4.
Input/Output
[time limit] 4000ms (py)
[input] array.integer a
Guaranteed constraints:
2 <= a.length <= 25,
0 <= a[i] <= 100.
[output] integer"""
def zigzag(a):
"""
>>> zigzag([9, 8, 8, 5, 3, 5, 3, 2, 8, 6])
4
>>> zigzag([2, 3, 1, 0, 2])
3
>>> zigzag([1, 2, 3, 2, 1])
3
>>> zigzag([2, 3, 1, 4, 2])
5
>>> zigzag([1, 2, 0, 3, 2, 1, 3, 2, 4, 0])
6
>>> zigzag([1, 2])
2
>>> zigzag([1, 2, 1])
3
>>> zigzag([1, 1])
1
"""
# time: O(n)
# space: O(1)
longest = 1
curr_length = 1
if len(a) == 2 and a[0] != a[1]:
return len(a)
for i in range(len(a)-2):
prev = a[i]
curr = a[i+1]
nxt = a[i+2]
if (prev < curr and curr > nxt) or (prev > curr and curr < nxt):
if nxt == a[-1]:
curr_length += 2
else:
curr_length += 1
longest = max(longest, curr_length)
else:
curr_length += 1
longest = max(longest, curr_length)
curr_length = 1
return longest
def zigzag_recursive(a):
"""
>>> zigzag_recursive([9, 8, 8, 5, 3, 5, 3, 2, 8, 6])
4
>>> zigzag_recursive([2, 3, 1, 0, 2])
3
>>> zigzag_recursive([1, 2, 3, 2, 1])
3
>>> zigzag_recursive([2, 3, 1, 4, 2])
5
>>> zigzag_recursive([1, 2, 0, 3, 2, 1, 3, 2, 4, 0])
6
>>> zigzag_recursive([1, 2])
2
>>> zigzag_recursive([1, 2, 1])
3
>>> zigzag_recursive([1, 1])
1
"""
# time: O(n)
# space: O(n)
if len(a) < 2:
return len(a)
if len(a) == 2 and a[0] != a[1]:
return len(a)
longest = 1
i = 1
good = True
while good and i < len(a) - 1:
curr = a[i]
prev = a[i-1]
nxt = a[i+1]
if (prev < curr and curr > nxt) or (prev > curr and curr < nxt):
i +=1
if i == len(a)-1:
longest += 1
else:
good = False
longest += 1
return max(longest, zigzag_recursive(a[i:]))
if __name__ == "__main__":
import doctest
results = doctest.testmod()
if not results.failed:
print "All tests passed"