ให้อาร์เรย์ nums ของจำนวนเต็มบวก หาความยาว prefix ยาวที่สุด ที่ถ้าลบสมาชิก 1 ตัวออก จะทำให้ทุกตัวเลขที่ปรากฏมีความถี่เท่ากัน (ถ้าไม่เหลือสมาชิก ถือว่าความถี่เท่ากันที่ 0)
เช่น [3,3,2,2,6,4,4,6] เอาต์พุต = 7 ลบ 6 ตัวที่ 4 ได้ [3,3,2,2,4,4] ทุกตัวปรากฏ 2 ครั้ง
วิธีแก้ − นับความถี่แต่ละตัว (cnt) และนับจำนวนตัวที่มีความถี่เท่าไหร่ (freq) ตรวจสอบเงื่อนไข 3 กรณี
ตัวอย่าง
#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