Replace Each Element with the Maximum Element to Its Right
Implement replaceWithGreatestOnRight
Given an array
nums, return a new array where every element is replaced by the greatest value found anywhere to its right. The very last position has nothing to its right, so it always becomes -1.
Scanning right-to-left while keeping track of the biggest value seen so far avoids re-scanning the remaining array at every position.
Example 1:
Input: nums = [9,4,6,2,8]
Output: [8,8,8,8,-1]
Example 2:
Input: nums = [1,2]
Output: [2,-1]
Example 3:
Input: nums = [7,7,7]
Output: [7,7,-1]
+ 4 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 10⁵ - ●
-10⁹ ≤ nums[i] ≤ 10⁹ - ●
The last position in the result is always -1
nums =
[9, 4, 6, 2, 8]