Skip to content

2968. Apply Operations to Maximize Frequency Score 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int maxFrequencyScore(vector<int>& nums, long long k) {
    int ans = 0;
    long cost = 0;

    ranges::sort(nums);

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      cost += nums[r] - nums[(l + r) / 2];
      while (cost > k)
        cost -= nums[(l + r + 1) / 2] - nums[l++];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int maxFrequencyScore(int[] nums, long k) {
    int ans = 0;
    long cost = 0;

    Arrays.sort(nums);

    // For a window [l, r], the best choice to make the numbers in the range
    // equal is to make them all equal to the median in this range.
    for (int l = 0, r = 0; r < nums.length; ++r) {
      cost += nums[r] - nums[(l + r) / 2];
      while (cost > k)
        cost -= nums[(l + r + 1) / 2] - nums[l++];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def maxFrequencyScore(self, nums: list[int], k: int) -> int:
    nums.sort()
    ans = 0
    cost = 0

    l = 0
    for r, num in enumerate(nums):
      cost += num - nums[(l + r) // 2]
      while cost > k:
        cost -= nums[(l + r + 1) // 2] - nums[l]
        l += 1
      ans = max(ans, r - l + 1)

    return ans