Leetcode - Replace Elements with Greatest Element on Right Side
https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/
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]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | func replaceElements(arr [] int ) [] int { if len(arr) == 0 { return [] int {} } max := arr[len(arr)-1] result := make([] int , len(arr)) result[len(arr)-1] = -1 for i := len(arr)-2; i >= 0; i-- { result[i] = max if arr[i] > max { max = arr[i] } } return result } |