- Related Questions & Answers
- Maximum Frequency Stack in C++
- Maximum length subarray with LCM equal to product in C++
- Maximum subset with bitwise OR equal to k in C++
- Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k in C++
- Find maximum sum possible equal sum of three stacks in C++
- Maximum Primes whose sum is equal to given N in C++
- Maximum elements that can be made equal with k updates in C++
- Find element in a sorted array whose frequency is greater than or equal to n/2 in C++.
- Sort Characters By Frequency in C++
- Maximum count of equal numbers in an array after performing given operations in C++
- Flip Columns For Maximum Number of Equal Rows in Python
- Maximum sum subarray having sum less than or equal to given sums in C++
- Program to find maximum sum of two sets where sums are equal in C++
- Find maximum sum array of length less than or equal to m in C++
- Program to construct Frequency Stack in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array nums of positive integers, we have to return the longest possible length of an array prefix of given array nums, such that it is possible to delete exactly one element from this prefix so that every number that has appeared in it will have the same frequency. After removing one element if there are no remaining elements, it's still considered that every appeared number has the same frequency (0).

So, if the input is like [3,3,2,2,6,4,4,6], then the output will be 7, So if we remove element 6 from index 4, then the subarray will be [3,3,2,2,4,4] where all elements appeared two times.

To solve this, we will follow these steps −

maxf := 0, res := 0

Define maps cnt and freq

for initialize i := 0, when i < size of nums, update (increase i by 1), do −

x := nums[i]

(increase cnt[x] by 1)

f := cnt[x]

(increase freq[f] by 1)

decrease freq[f - 1] by 1

maxf := maximum of maxf and f

if maxf * freq[maxf] is same as i or (maxf - 1) * (freq[maxf - 1] + 1) is same as i or maxf is same as 1, then −

res := i + 1

return res

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; class Solution { public: int maxEqualFreq(vector<int>& nums) { int maxf = 0, res = 0; map<int, int> cnt, freq; for (int i = 0; i < nums.size(); i++) { int x = nums[i]; cnt[x]++; int f = cnt[x]; freq[f]++; freq[f - 1]--; maxf = max(maxf, f); if (maxf * freq[maxf] == i || (maxf - 1) * (freq[maxf - 1] + 1) == i || maxf == 1) { res = i + 1; } } return res; } }; main(){ Solution ob; vector<int> v = {3,3,2,2,6,4,4,6}; cout << (ob.maxEqualFreq(v)); }

{3,3,2,2,6,4,4,6}

7

Advertisements