647/670

647. Frequency of the Most Frequent Element

Medium

The frequency of a value is how many elements of the array are equal to it.

You are given an integer array nums and an integer k. In one operation you pick any index i and increase nums[i] by exactly 1. You may perform at most k operations in total, spread across any indices you like.

Return the largest frequency any single value can have after the operations are spent.

Example 1:

Input: nums = [1, 2, 4], k = 5

Output: 3

Explanation: Raise the 1 up to 4 (3 operations) and the 2 up to 4 (2 operations). All 5 operations are used and the array becomes [4, 4, 4], so the value 4 has frequency 3.

Example 2:

Input: nums = [1, 4, 8, 13], k = 5

Output: 2

Explanation: Any one of three plans yields a pair: 1 → 4 (3 ops), 4 → 8 (4 ops), or 8 → 13 (5 ops). No value can reach frequency 3 within 5 operations.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁵
  • 1 ≤ k ≤ 10⁵

Hints:

Operations only increase values, so if the final common value is v, the cheapest elements to convert are the ones closest to v from below. Sort the array and those elements become a contiguous block ending at v.

After sorting, turning every element of nums[l..r] into nums[r] costs nums[r]·(r − l + 1) − sum(nums[l..r]). Grow r one step at a time and advance l while that cost exceeds k — a sliding window whose both pointers only move forward.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 2, 4], k = 5

Expected output: 3