Weird Measurements (Medium)
InterviewTime limit2sMemory limit512 MB
Count the contiguous subarrays whose consecutive differences alternate in sign, with no zero differences allowed.
- Level
Medium5 of 10
- Topics
- Array, Two pointers, Implementation, Brute force
- Solved
- No attempts yet
Problem
"Almonds? Oh yeah, I have tried those before. Covered in chocolate." (Dudu, 2015)
Dudu is getting in shape for an upcoming trip to Thailand. As part of the plan he records his weight every morning.
Over some stretches of days the weight drops steadily, and over others it climbs steadily. Some stretches move strangely.
An interval of records is weird if it alternates between increasing and decreasing. For example, records of 1, 3, 2, 5, 1 on consecutive days are weird. Records of 1, 3, 5, 4 are not weird, because the value increases from 1 to 3 and then again from 3 to 5. Every interval of length 1 is weird.
If two neighbouring records are equal, that change is neither an increase nor a decrease, so an interval that contains both of them is not weird.
Given the sequence of records, count the weird intervals.
Input
The first line contains the length of the sequence, .
The second line contains the integers of the sequence, separated by spaces.
Output
Print the number of weird intervals on one line. An interval is a non-empty contiguous subsequence, and two intervals with a different start or end position count separately even when their values are the same.
Hint
For the sequence 1 4 4 2 5 2 1 the weird intervals are [1], [1, 4], [4], [4], [4, 2], [4, 2, 5], [4, 2, 5, 2], [2], [2, 5], [2, 5, 2], [5], [5, 2], [2], [2, 1], [1], so the answer is 15. Two different intervals hold the single record 4, and both of them are counted.