Thursday, 29 July 2021

Leaders in an array

An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader.
For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main(){
    int arr[] = {18, 16, 17, 4, 3, 5, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    int maxSoFar = arr[n - 1];
    cout << maxSoFar << " ";
    for(int i = n - 2; i >= 0 ; i--){
        if(arr[i] > maxSoFar){
            cout << arr[i] << " ";
            maxSoFar = arr[i];
        }
    }
    cout << endl;
    return 0;
}
Share:

1 comment:

  1. Great insights on identifying leaders in an array! Using ViVeTool can streamline data processing and make analyzing these patterns much easier.

    ReplyDelete

Contact Me

Name

Email *

Message *

Popular Posts