code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

1299 Replace Elements With Greatest Element On Right Side

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const replaceElementsWithGreatestElementOnRightSide = arr => {
  let rightMax = -1
  for (let i = arr.length - 1; i >= 0; i--) {
    const newMax = Math.max(rightMax, arr[i])
    arr[i] = rightMax
    rightMax = newMax
  }
  return arr
}

console.log(replaceElementsWithGreatestElementOnRightSide([17, 18, 5, 4, 6, 1]))

Created 2022-03-19T10:55:16+00:00 · Edit