1691. Staircase Chain Totals
A trail crosses a row of hills, and nums[i] is the altitude of hill i (it may be negative). A hiker who stands on hill i always walks to the nearest hill further to the right that is strictly higher than her current one, and repeats this until no higher hill lies ahead. Hills of equal altitude do not count as higher. She adds up the altitude of every hill she stands on, including the one she started from. Return a long[] of the same length as nums whose entry i is the total for a walk that starts at hill i. Walking every chain separately is too slow when the altitudes keep rising, so aim for O(n) time and O(n) extra space.
Example 1
- Input:
- nums = [3,1,4,1,5]
- Output:
- [12,10,9,6,5]
- Explanation:
From the 3 the hiker reaches 4 and then 5 (12); from the first 1 she reaches 4 and then 5 (10); from 4 she reaches 5 (9); the second 1 goes straight to 5 (6); the final 5 has nothing higher ahead (5).
Example 2
- Input:
- nums = [5,5,5]
- Output:
- [5,5,5]
- Explanation:
Equal altitudes are not higher, so no walk moves and every total is just the starting altitude.
Example 3
- Input:
- nums = [-2,-5,-1,-1,7]
- Output:
- [4,1,6,6,7]
- Explanation:
From -2 the nearest higher hill is -1 (index 2), then 7, giving 4; from -5 the walk is -5, -1, 7 for 1; both -1 hills jump to 7 for 6 each; the 7 stays alone.
Constraints
1 ≤ nums.length ≤ 105
-109 ≤ nums[i] ≤ 109
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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)