Replace Elements With Greatest Element on Right Side Using Java

  • Home /
  • Blog Posts /
  • Replace Elements with Greatest Element on Right Side using Java

The challenge

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Example 1:

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]

Constraints:

  • 1 <= arr.length <= 10^4
  • 1 <= arr[i] <= 10^5

The solution

class Solution {
    public int[] replaceElements(int[] arr) {
        // loop through all array items
        for (int i=0; i<arr.length; i++) {
            
            // if the last item
            if (i==arr.length-1) {
                // set the last item
                arr[i] = -1;
            } else {

                // set a variable to check biggest value against
                int biggest = 0;
                // loop through the internal looperr
                for(int j=i+1; j<arr.length; j++) {
                    // if the next value is bigger than our
                    // current biggest, then update it
                    if (arr[j]>biggest) biggest = arr[j];
                }
                // replace the current value with the biggest found
                arr[i] = biggest;
            }
        }
        // return our array of ints
        return arr;
    }
}