741. Even-Step Slices
A hiker logs the altitude at every trail marker in the array nums. A steady stretch is a run of at least three consecutive markers in which the altitude changes by exactly the same amount from each marker to the next (the amount may be positive, negative or zero).
Return how many different steady stretches exist. Two stretches are different when they start or end at different marker positions, and a long steady run contains many shorter steady stretches that all count. Return 0 if there are none.
Aim for time O(n) and extra space O(1), where n is the length of nums.
Example 1
- Input:
- nums = [3,8,13,18,23,40]
- Output:
- 6
- Explanation:
Markers 3, 8, 13, 18, 23 step by 5, giving 6 stretches of length 3, 4 or 5 (3 + 2 + 1); the trailing 40 breaks the pattern.
Example 2
- Input:
- nums = [6,6,6,6,1,2]
- Output:
- 3
- Explanation:
The four 6s form three stretches of length 3 or 4 (2 + 1), and the tail 1, 2 is too short.
Example 3
- Input:
- nums = [12,9,4,1]
- Output:
- 0
- Explanation:
No three consecutive markers share the same step, so the answer is 0.
Constraints
1 ≤ nums.length ≤ 60000
-109 ≤ nums[i] ≤ 109
The answer always fits in a 32-bit signed integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)