Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array

LOGIC:

It requires two loops.

1)The first loop iterates through the elements in the array one by one.
2)The second loop finds the greatest element after the current element.

The last number in the array is replaced by -1 since there is no element to the left of the last element.


PROGRAM

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    long n;
    cin>>n;
    int a[n];
    int i;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    int j;
    for(i=0;i<n-1;i++)
    {
        int great=a[i+1];
        for(j=i+1;j<n;j++)
        {
            if(a[j]>great)
            {
                great=a[j];
            }
        }
        a[i]=great;
    }
    a[n-1]=-1;
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }

    return 0;
}


OUTPUT:

18
26 75 37 29 8 -67 31 42 72 57 -89 45 32 61 -64 25  48 -94 
 
75 72 72 72 72 72 72 72 61 61 61 61 61 48 48 48 -94 -1
 
15
1 2 3 10 4 5 6 -1 7 8 12 15 -9 45 9
 
45 45 45 45 45 45 45 45 45 45 45 45 45 9 -1  
 
 
 
  

Comments

Popular posts from this blog

C program to print the following Pattern

c++ program to print string along the diagonals of the matrix.

Kollywood Game