Upadate array elements with next greatest element on its right
Update the array
elements by the next greatest number in the given array…Since there
is no successive element for last array element print “-1”..
Sample
Input:{4,5,16,10,7,5,3}
Sample
output:{16,16,10,7,5,3,-1}
Code:
import java.util.Arrays;
public class Program1 {
public static void main (String[] args){
int a[] = {4,5,16,10,7,5,3};
for(int i=0; i<a.length-1; i++){
int max = a[i+1];
for(int j=i+2; j<a.length; j++){
if(a[j]> max){
max = a[j];
}
}
a[i] = max;
}
a[a.length-1] = -1;
System.out.print(Arrays.toString(a));
}
}
Output:
[16, 16, 10, 7, 5, 3, -1]
Comments
Post a Comment