
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Replace Elements with Greatest Element on Right Side in C++
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 −
#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]
- Related Articles
- Replace every element with the least greater element on its right using C++
- Count smaller elements on right side using Set in C++ STL
- Number of Larger Elements on right side in a string in C++
- Finding the element larger than all elements on right - JavaScript
- Point arbit pointer to greatest value right side node in a linked list in C++
- JAVA Program to Replace Element of Integer Array with Product of Other Elements
- Program to replace each element by smallest term at left side in Python
- How to perform right click on an element with Actions in Selenium?
- How to perform right click on an element in Selenium with python?
- C++ program to replace an element makes array elements consecutive
- How to replace a DOM element with the specified HTML or DOM elements using jQuery?
- Float an element to the right on different screens with Bootstrap
- Why Indian Vehicles steering is on Left Side while few Foreign countries in right side?
- Golang Program to pad a string with 0's on the right side
- How to replace one vector elements with another vector elements in R?

Advertisements