Generate an array consisting of most frequent greater elements present on the right side of each array element | C ++ program for the above approach ; Function to generate an array containing the most frequent greater element on the right side of each array element ; Stores the generated array ; Traverse the array arr [ ] ; Store the result for the current index and its frequency ; Iterate over the right subarray ; Store the frequency of the current array element ; If the frequencies are equal ; Update ans to smaller of the two elements ; If count of new element is more than count of ans ; Insert answer in the array ; Print the resultant array ; Driver Code ; Given Input
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int arr [ ] , int n ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { int ans = -1 , old_c = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] > arr [ i ] ) { int curr_c = count ( & arr [ j ] , & arr [ n ] , arr [ j ] ) ; if ( curr_c == old_c ) { if ( arr [ j ] < ans ) ans = arr [ j ] ; } if ( curr_c > old_c ) { ans = arr [ j ] ; old_c = curr_c ; } } } v . push_back ( ans ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) cout << v [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 4 , 5 , 2 , 25 , 10 , 5 , 10 , 3 , 10 , 5 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findArray ( arr , size ) ; return 0 ; }