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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;
    }
}