Replace Elements with Greatest Element on Right Side using Java

0 min read 164 words

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;
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags