DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Replace Elements with Greatest Element on Right Side



let replaceElements = function (arr) {
  let arrayLength = arr.length;
  let max = Number.NEGATIVE_INFINITY;

  for (let i = 0; i < arr.length; i++) {
    max = Number.NEGATIVE_INFINITY;
    for (let j = i + 1; j < arrayLength; j++) {
      if (max < arr[j]) {
        max = arr[j];
      }
    }
    arr[i] = max;
  }
  arr[arrayLength - 1] = -1;
};

var replaceElements_2 = function (arr) {
  let max = arr[arr.length - 1];

  for (let j = arr.length - 2; j >= 0; --j) {
    let curr = arr[j];
    arr[j] = max;
    max = Math.max(max, curr);
  }

  arr[arr.length - 1] = -1;
  return arr;
};

console.log(replaceElements([17]));
console.log(replaceElements_2([17, 18, 1, 3, 4, 5, 6]));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)