You are 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 = [2,4,5,3,1,2]
Output: [5,5,3,2,2,-1]Example 2:
Input: arr = [3,3]
Output: [3,-1]Constraints:
1 <= arr.length <= 10,0001 <= arr[i] <= 100,000Before attempting this problem, you should be comfortable with:
For each element at index i, we need to find the maximum value among all elements to its right. The most straightforward approach is to scan every element to the right for each position using index j. The last element has no elements to its right, so it becomes -1.
ans of the same size as the input.i, initialize rightMax to -1.j from i + 1 to the end, updating rightMax with the maximum value found.rightMax in ans at position i.ans array.By traversing right to left, we can maintain a running maximum of all elements seen so far in rightMax. When we visit position i, the current running maximum represents the greatest element to the right of i. We then update rightMax to include arr[i] for the next iteration. This eliminates redundant scanning.
ans of the same size as the input.rightMax to -1 (the value for the last position).i.i, store the current rightMax in ans.rightMax to be the maximum of itself and arr[i].ans array.Processing the array from left to right requires recalculating the maximum of all right elements for each position, resulting in O(n^2) time complexity. The optimal approach traverses right to left, maintaining a running maximum in a single pass.
When traversing right to left, the current element's value must be stored in the result before updating rightMax. Updating rightMax first causes the current element to incorrectly include itself in its own replacement value.