Replace Elements with Greatest Element on Right Side

easy array suffix max

Problem

You are given an integer array arr. Replace every element with the greatest value that appears among the elements strictly to its right, and replace the last element with -1 because nothing lies to its right. Return the modified array (length up to 10⁴, values between 1 and 10⁵).

Inputarr = [17, 18, 5, 4, 6, 1]
Output[18, 6, 6, 6, 1, -1]
To the right of 17 the largest value is 18, to the right of 5 it is 6, and the last slot gets −1.

def replace_elements(arr):
    mx = -1                       # greatest value seen on the right
    for i in range(len(arr) - 1, -1, -1):
        cur = arr[i]              # stash the original value
        arr[i] = mx               # overwrite with the suffix max
        mx = max(mx, cur)         # fold the stash into the max
    return arr
function replaceElements(arr) {
  let mx = -1;                    // greatest value seen on the right
  for (let i = arr.length - 1; i >= 0; i--) {
    const cur = arr[i];           // stash the original value
    arr[i] = mx;                  // overwrite with the suffix max
    mx = Math.max(mx, cur);       // fold the stash into the max
  }
  return arr;
}
int[] replaceElements(int[] arr) {
    int mx = -1;                  // greatest value seen on the right
    for (int i = arr.length - 1; i >= 0; i--) {
        int cur = arr[i];         // stash the original value
        arr[i] = mx;              // overwrite with the suffix max
        mx = Math.max(mx, cur);   // fold the stash into the max
    }
    return arr;
}
vector<int> replaceElements(vector<int>& arr) {
    int mx = -1;                  // greatest value seen on the right
    for (int i = (int)arr.size() - 1; i >= 0; i--) {
        int cur = arr[i];         // stash the original value
        arr[i] = mx;              // overwrite with the suffix max
        mx = max(mx, cur);        // fold the stash into the max
    }
    return arr;
}
Time: O(n) Space: O(1)