Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Array Exercises: Replace every element with the next greatest element in a given array of integers

Java Array: Exercise-53 with Solution

Write a Java program to replace every element with the next greatest element (from right side) in a given array of integers. There is no element next to the last element, therefore replace it with -1.

Sample Solution:

Java Code:

import java.io.*;
import java.util.Arrays;
public class Main 
{
   public static void main (String[] args)
    {
        int nums[] = {45, 20, 100, 23, -5, 2, -6};
		int result[];
		System.out.println("Original Array ");
        System.out.println(Arrays.toString(nums));

        result = next_greatest_num(nums);
        System.out.println("The modified array:");
        System.out.println(Arrays.toString(result));
    }
 
    static int [] next_greatest_num(int arr_nums[])
    {
        int size = arr_nums.length;
        int max_from_right_num =  arr_nums[size-1];
        arr_nums[size-1] = -1;
 
        for (int i = size-2; i >= 0; i--)
        {
            int temp = arr_nums[i];
            arr_nums[i] = max_from_right_num;
            if(max_from_right_num < temp)
            max_from_right_num = temp;
        }
		return arr_nums;
    } 
}

Sample Output:

                                                                              
Original Array 
[45, 20, 100, 23, -5, 2, -6]
The modified array:
[100, 100, 23, 2, 2, -6, -1]

Flowchart:

Flowchart: Replace every element with the next greatest element in a given array of integers

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to separate even and odd numbers of a given array of integers. Put all even numbers first, and then odd numbers.
Next: Write a Java program to check if a given array contains a subarray with 0 sum.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe