I think I have a brute force solution to the problem but I can't think of a more optimal solution
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
[input] array.integer a
constraints:
2 ≤ a.length ≤ 25,
0 ≤ a[i] ≤ 100.
Here is my brute force solution
def zigzag(input):
current_longest = 0
longest_subset = []
input_length = len(input)
for x in range(input_length):
current_list = input[x:]
for pos_a, num_a in enumerate(current_list):
subset = [num_a, ]
prev_trend = None
for pos_b, num_b in enumerate(current_list[pos_a + 1:]):
last_number = subset[-1]
if last_number == num_b:
# print "[DUPE] current subset state", subset, "comparing ->", subset[-1], num_b
break
if last_number > num_b:
cur_trending = "down"
else:
cur_trending = "up"
if prev_trend:
# compare trends
if prev_trend == cur_trending:
# print "[TREND] current subset state", subset, "comparing ->", subset[-1], num_b
break
else:
prev_trend = cur_trending
else:
# initial trend set
prev_trend = cur_trending
subset.append(num_b)
if len(subset) > current_longest:
current_longest = len(subset)
longest_subset = subset
print current_longest, longest_subset
zigzag([9, 8, 8, 5, 3, 5, 3, 2, 8, 6])
zigzag([4, 2, 3, 1, 5, 3])