Maps app~10 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
A maps app records the height of a hiking trail every 100 metres. The samples come in the order of the walk. Some samples can be below sea level, so a height can be negative.
You want to show the highest point of the walk and how far along it comes. If the same highest height is recorded more than once, show the first time.
Write highest_sample(heights).
heights[i] is the height of the sample at position i + 1. Positions start at 1.Input: heights = [3, 9, 2, 9, 5]
Output: [9, 2]The height 9 appears at positions 2 and 4. The earlier one is the answer.
| Position | Height | Highest so far | Position of it |
|---|---|---|---|
| 1 | 3 | 3 | 1 |
| 2 | 9 | 9 | 2 |
| 3 | 2 | 9 | 2 |
| 4 | 9 | 9 | 2 |
| 5 | 5 | 9 | 2 |
Input: heights = [7]
Output: [7, 1]One sample is the highest, at position 1.
Input: heights = [-5, -2, -9]
Output: [-2, 2]All heights are negative. The highest is -2, at position 2.
1 ≤ length of heights ≤ 10^5-10^6 ≤ heights[i] ≤ 10^6A list can have 100,000 samples. Testing each sample against all the others reads about 5 x 10^9 values on a list in rising order. That is too slow.
One pass over the list reads 10^5 values. Heights fit in a 32-bit integer.