1299. Replace Elements with Greatest Element on Right Side #
Problem #
Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^41 <= arr[i] <= 10^5
Problem Summary #
Given an array arr, replace each element with the greatest element on its right; if it is the last element, replace it with -1. After completing all replacement operations, return this array.
Note:
- 1 <= arr.length <= 10^4
- 1 <= arr[i] <= 10^5
Solution Approach #
- Given an array, replace every element with the greatest element to its right, and fill the last position with -1. Finally, output the changed array.
- Easy problem; just operate according to the problem statement.
Code #
func replaceElements(arr []int) []int {
j, temp := -1, 0
for i := len(arr) - 1; i >= 0; i-- {
temp = arr[i]
arr[i] = j
j = max(j, temp)
}
return arr
}