27. Best View to the Right
Along a hillside trail there are lookout points, and the height of each one is given in the array in the order you walk them. From any lookout, a hiker wants to know the height of the tallest lookout that lies further along the trail; for the very last lookout there is nothing ahead.
Write a method replaceWithRightMax that takes the array nums of heights and returns a new array of the same length. Each position i of the result holds the greatest value among nums[i+1], nums[i+2], ... to its right, and the last position holds -1.
Example 1
- Input:
- nums = [17,18,5,4,6,1]
- Output:
- [18,6,6,6,1,-1]
- Explanation:
Looking right from position 0 the tallest is 18; from position 1 it is 6; and so on. The last position has nothing to its right, so it becomes -1.
Example 2
- Input:
- nums = [9]
- Output:
- [-1]
- Explanation:
A single lookout has nothing ahead of it.
Constraints
1 ≤ nums.length ≤ 1000
1 ≤ nums[i] ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)