Wednesday, February 17, 2021

Replace every element with the next greatest

 Replace every element with the next greatest.

Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. Since there is no element next to the last element, replace it with -1. For example, if the array is {16, 17, 4, 3, 5, 2}, then it should be modified to {17, 5, 5, 5, 2, -1}.

public static int[] replaceGreatestNumber(int[] a) {

int n = a.length;

int max = a[n-1];

a[n-1] = -1;

for(int i=n-2; i>=0; i--) {

int temp = a[i];

a[i] = max;

if(temp > max) {

max = temp;

}

}

return a;

}

No comments:

Post a Comment