> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/06-05-2022-1299.-replace-elements-with-greatest-element-on-right-side.md).

# 06/05/2022 1299. Replace Elements with Greatest Element on Right Side

Method: scan the loop from the end. set max = -1 first. use tmp to get the current value, set arr\[i] to max and get the max by comparing tmp and current max value.

Time O(n) Space O(1)

```
// Some code
class Solution {
    public int[] replaceElements(int[] arr) {
        int max = -1;
        for (int i = arr.length - 1; i >= 0; i--){
            int tmp = arr[i];
            arr[i] = max;
            max = Math.max(max, tmp)
            
        }
        return arr;
    }
}
```
