Skip to content

1299. Replace Elements with Greatest Element on Right Side 👍

  • Time:
  • Space:
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  vector<int> replaceElements(vector<int>& arr) {
    int maxOfRight = -1;
    for (int i = arr.size() - 1; i >= 0; --i)
      maxOfRight = max(maxOfRight, exchange(arr[i], maxOfRight));
    return arr;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int[] replaceElements(int[] arr) {
    int maxOfRight = -1;
    for (int i = arr.length - 1; i >= 0; --i) {
      int a = arr[i];
      arr[i] = maxOfRight;
      maxOfRight = Math.max(maxOfRight, a);
    }
    return arr;
  }
}
1
2
3
4
5
6
class Solution:
  def replaceElements(self, arr: List[int]) -> List[int]:
    maxOfRight = -1
    for i in reversed(range(len(arr))):
      arr[i], maxOfRight = maxOfRight, max(maxOfRight, arr[i])
    return arr