You are given a list that contains some permutation of the numbers 1 \dots n. Your task is to count the number of alternating subarrays.
Here alternating means that the values in the subarray alternate between being bigger than the previous value and being smaller than the previous value. Expressed in another way, an alternating subarray cannot contain three consecutive values in increasing order or in decreasing order.
The goal is an algorithm with time complexity O(n).
In a file alternation.py
, implement a function count
that returns the number of alternating subarrays.
def count(t): # TODO if __name__ == "__main__": print(count([1,2,3,4])) # 7 print(count([1,4,2,5,3])) # 15 print(count([7,2,1,3,5,4,6])) # 17
Explanation: On the list [1,2,3,4], only subarrays of length one (4 of them) or length two (3 of them) are alternating, since all longer subarrays contain three consecutive values in increasing order. On the list [1,4,2,5,3], every subarray is alternating since the whole list is alternating.