Replace Elements with Greatest Element on Right Side in C++

C++Server Side ProgrammingProgramming

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 −

  • We will read the array element from right to left.
  • take e := -1
  • for i := n – 1 to 0
    • temp := e
    • e := max between e and array[i]
    • array[i] := temp
  • return array

Example

Let us see the following implementation to get better understanding −

 Live Demo

#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)) ;
}

Input

[5,17,40,6,3,8,2]

Output

[40,40,8,8,8,2,-1]
raja
Published on 20-Jan-2020 11:29:34
Advertisements