# 1299. 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]
Explanation:

- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
``````

Example 2:

``````Input: arr = [400]
Output: [-1]
Explanation: There are no elements to the right of index 0.
``````

Constraints:

• `1 <= arr.length <= 10**4`
• `1 <= arr[i] <= 10**5`

Hint 1

Loop through the array starting from the end.

Hint 2

Keep the maximum value seen so far.

## 解法解析

### 解法範例

#### Go

``````func replaceElements(arr []int) []int {
mx := -1
for i := len(arr) - 1; i >= 0; i-- {
if arr[i] > mx {
arr[i], mx = mx, arr[i]
} else {
arr[i] = mx
}
}
return arr
}
``````

#### JavaScript

``````/**
* @param {number[]} arr
* @return {number[]}
*/
var replaceElements = function (arr) {
let mx = -1;
for (let i = arr.length - 1; i >= 0; i--) {
[arr[i], mx] = [mx, Math.max(arr[i], mx)];
}
return arr;
};
``````

#### Kotlin

``````class Solution {
fun replaceElements(arr: IntArray): IntArray {
var mx: Int = -1
for (i in arr.size - 1 downTo 0) {
val tmp = arr[i]
arr[i] = mx
mx = maxOf(mx, tmp)
}
return arr
}
}
``````

#### PHP

``````class Solution
{

/**
* @param Integer[] \$arr
* @return Integer[]
*/
function replaceElements(\$arr)
{
\$mx = -1;
for (\$i = count(\$arr) - 1; \$i >= 0; \$i--) {
\$temp = \$mx;
\$mx = max(\$arr[\$i], \$mx);
\$arr[\$i] = \$temp;
}
return \$arr;
}
}
``````

#### Python

``````class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
mx = -1
for i in range(len(arr) - 1, -1, -1):
arr[i], mx = mx, max(mx, arr[i])
return arr
``````

#### Rust

``````impl Solution {
pub fn replace_elements(arr: Vec<i32>) -> Vec<i32> {
let mut mx = -1;
let mut res = vec![-1; arr.len()];
for i in (0..arr.len()).rev() {
res[i] = mx;
mx = std::cmp::max(arr[i], mx);
}
res
}
}
``````

#### Swift

``````class Solution {
func replaceElements(_ arr: [Int]) -> [Int] {
var mx: Int = -1
var res: [Int] = arr
for i in (0..<arr.count).reversed() {
res[i] = mx
mx = max(mx, arr[i])
}
return res
}
}
``````