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^4`

`1 <= arr[i] <= 10^5`

**Solution: Scan from right to left**

Time complexity: O(n)

Space complexity: O(1)

## C++

1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua class Solution { public: vector<int> replaceElements(vector<int>& arr) { int g = -1; for (int i = arr.size() - 1; i >= 0; --i) g = max(g, exchange(arr[i], g)); return arr; } }; |