leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1838.cpp (1187B)


      1 static const auto _ = [] {
      2     cin.tie(0);
      3     ios::sync_with_stdio(0);
      4     return 0;
      5 }();
      6 class Solution {
      7   public:
      8     int maxFrequency(vector<int> &nums, int k) const {
      9         static long long prefix[100001];
     10         const int n = nums.size();
     11 
     12         memset(prefix, 0x00, sizeof(prefix));
     13         for (int i = 0; i < n; i++)
     14             prefix[nums[i]]++;
     15 
     16         for (int i = 0, j = 0; i <= 100000; i++) {
     17             while (prefix[i] > 0) {
     18                 nums[j++] = i, prefix[i]--;
     19             }
     20         }
     21 
     22         prefix[0] = 0;
     23         for (int i = 1; i < n; i++)
     24             prefix[i] = nums[i - 1] + prefix[i - 1];
     25 
     26         int res = 0;
     27         for (int crnt = 0; crnt < n; crnt++) {
     28             int low = 0, high = crnt - 1;
     29             while (low <= high) {
     30                 const int mid = low + (high - low) / 2;
     31                 const long long left = crnt - mid;
     32                 const long long sum = prefix[crnt] - prefix[mid];
     33                 if (left * nums[crnt] - sum <= k)
     34                     high = mid - 1;
     35                 else
     36                     low = mid + 1;
     37             }
     38             res = max(res, crnt - high);
     39         }
     40 
     41         return res;
     42     }
     43 };