leetcode

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

2779.cpp (1056B)


      1 // Binary search: O(n * logn)
      2 class Solution {
      3   public:
      4     int maximumBeauty(vector<int> &nums, int k) const {
      5         sort(begin(nums), end(nums));
      6         int res = 1;
      7 
      8         for (int i = 0; i < size(nums); i++) {
      9             const auto it = upper_bound(begin(nums), end(nums), 2 * k + nums[i]);
     10             res = max(res, (int)distance(begin(nums) + i, it));
     11         }
     12 
     13         return res;
     14     }
     15 };
     16 
     17 // Line sweep: O(n)
     18 class Solution {
     19   public:
     20     int maximumBeauty(const vector<int> &nums, int k) const {
     21         int mini = INT_MAX, maxi = INT_MIN;
     22         static int count[200002];
     23 
     24         memset(count, 0x00, sizeof(count));
     25         for (const int n : nums) {
     26             const int a = max(n - k, 0);
     27             const int b = n + k + 1;
     28 
     29             count[a]++;
     30             count[b]--;
     31 
     32             mini = min(mini, a);
     33             maxi = max(maxi, b);
     34         }
     35 
     36         int res = 1;
     37         for (int i = mini, acc = 0; i <= maxi; i++) {
     38             acc += count[i];
     39             res = max(res, acc);
     40         }
     41 
     42         return res;
     43     }
     44 };