Replace Elements with Greatest Element on Right Side
Given an array arr, replace every element with the greatest element among the elements to its right, and replace the last element with -1. Return the array after doing so.
30:00
Replace Elements with Greatest Element on Right Side
Given an array arr, replace every element with the greatest element among the elements to its right, and replace the last element with -1. Return the array after doing so.
Example 1:
Input: {"arr":[17,18,5,4,6,1]}
Output: [18,6,6,6,1,-1]
Constraints:
1≤arr.length≤104
1≤arr[i]≤105
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"arr":[17,18,5,4,6,1]}
Walk from the right end. mx holds the largest value seen to the right; nothing is to the right of the last element yet, so mx starts at -1.
walk right to left, carrying the tallest value seen
17
0
18
1
5
2
4
3
6
4
1
5
bars = original values, green boxes = what each slot now holds, dashed line = mx