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

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```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;
}
}
```Code language: Java (java)```
Tags:
Subscribe
Notify of