# LeetCode: Replace Elements with Greatest Element on Right Side Solution

Backward iteration, create an array of right max

## Approach

I prefer reverse array and iterate forward

## Implementation (in-place operation)

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} arr3 * @return {number[]}4 */5var replaceElements = function (arr) {6  arr.reverse()7
8  let max = -19
10  for (let i = 0; i < arr.length; i++) {11    let temp = arr[i]12    arr[i] = max13    max = Math.max(max, temp)14  }15
16  return arr.reverse()17}```

## Implementation (create new array)

```1/**2 * @param {number[]} arr3 * @return {number[]}4 */5var replaceElements = function (arr) {6  const reversedArr = [...arr].reverse()7
8  let max = -19
10  const rightMax = reversedArr.map((_, index) => {11    if (index === 0) return -112
13    max = Math.max(max, reversedArr[index - 1])14    return max15  })16
17  return rightMax.reverse()18}```

leetcode

array

## Next Post

LeetCode: Sort Array By Parity

Jul 27, 2021

Filter and concat

## Previous Post

LeetCode: Valid Mountain Array

Jul 25, 2021

Flagging

Search Posts