1299. Replace each element with the largest element on the right (C++)
1 topic description
Give you an array arr, please replace each element with the largest element to the right, if it is the last element, replace it with -1.
After completing all the replacement operations, please return to this array.
2 Example description
2.1 Example 1
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation:
- Element with subscript 0 --> The largest element on the right is the element with subscript 1 (18)
- Element with subscript 1 --> The largest element on the right is the element with subscript 4 (6)
- Element with subscript 2 --> The largest element on the right is the element with subscript 4 (6)
- The element with subscript 3 --> The largest element on the right is the element with subscript 4 (6)
- Element with subscript 4 --> The largest element on the right is the element with subscript 5 (1)
- Elements with subscript 5 --> There are no other elements on the right side, replace with -1
2.2 Example 2
Input: arr = [400]
Output: [-1]
Explanation: There are no other elements to the right of the element with subscript 0.
3 Problem solving tips
1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5
4 Detailed source code (C++)
class Solution {
public:
vector<int> replaceElements(vector<int>& arr) {
vector<int> res ;
int max = 0 , i = 0;
for ( i = 0 ; i < arr.size() - 1 ; i ++ )
{
for ( int j = i + 1 ; j < arr.size() ; j ++ )
{
if ( arr[j] > max )
{
max = arr[j];
}
}
res.push_back( max );
max = 0 ;
}
res.push_back( -1 );
return res ;
}
};