code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

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