Suppose we have an array A. We have to replace every element by the greatest element on the right side of this element. And replace the last one by -1. So if A = [5, 17, 40, 6, 3, 8, 2], then it will be [40,40,8,8,8,2,-1]
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<int> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> replaceElements(vector<int>& arr) { int rep = -1; int n = arr.size(); for(int i = n - 1; i >= 0; i--){ int temp = rep; rep = max(rep, arr[i]); arr[i] = temp; } return arr; } }; main(){ Solution ob; vector<int> c = {5,17,40,6,3,8,2}; print_vector(ob.replaceElements(c)) ; }
[5,17,40,6,3,8,2]
[40,40,8,8,8,2,-1]