Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Most frequent element in an array #432

Merged
merged 3 commits into from
Oct 2, 2021
Merged

Most frequent element in an array #432

merged 3 commits into from
Oct 2, 2021

Conversation

ayush-1909
Copy link
Contributor

Problem

Calculate the Most frequent element in an array.

Solution

#include <bits/stdc++.h>
using namespace std;

int mostFreq(int arr[], int n)
{
// Sorting
sort(arr, arr + n);

// using linear traversal
int max_count = 1, res = arr[0], curr_count = 1;
for (int i = 1; i < n; i++) {
    if (arr[i] == arr[i - 1])
        curr_count++;
    else {
        if (curr_count > max_count) {
            max_count = curr_count;
            res = arr[i - 1];
        }
        curr_count = 1;
    }
}

// if most freq = last element
if (curr_count > max_count)
{
    max_count = curr_count;
    res = arr[n - 1];
}

return res;

}

// driver program
int main()
{
//array
int arr[] = { 1, 7, 2, 3, 3, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << mostFreq(arr, n);
return 0;
}

Changes proposed in this Pull Request :

Added a new program in the c++ directory

@fineanmol fineanmol merged commit 103dfb4 into fineanmol:master Oct 2, 2021
@fineanmol fineanmol added the hacktoberfest-accepted Accept for hacktoberfest, will merge later label Oct 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hacktoberfest-accepted Accept for hacktoberfest, will merge later
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants