Search code examples
c++loopsmaxvarfind-occurrences

How to find the occurrence count of sequence's largest element in C++?


C++ beginner here. I'm trying to write a program without the usage of arrays that would take a N number and allow the user to write a sequence of elements consisting of the N number (e.g. the N is 5, then the sequence of elements should be consisted of 5 integers (e.g. 8,21,7,21,10)). Then the program should count how much does the max element of the sequence occurr (in the example the output should be 2, because the max number is 21, which occurrs 2 times). Here is the code I've wrote so far, which detects the max nubmer of the sequence.

#include <iostream>
#include <limits.h>
using namespace std;

int main() {
  int n , n_seq, count = 0;
  int max = INT_MIN;
  
  
  cin>>n;
  for(int i = 0; i < n; i++)
  {
    cin>>n_seq;

    if(n_seq > max)
    {
      
      max = n_seq;
      
    }    
  }  
  cout<<max;
}

But I can't figure out the rest on how to increment the count variable each time the max nubmer occurs.


Solution

  • You need to increase the count when n_seq == max and when you encounter a new maximum number you need to reset the counter:

    if(n_seq > max)
    {
      counter = 1;
      max = n_seq;
      
    } else if (n_seq == max) {
       ++count;
    }