You are given an array of positive whole numbers nums and a budget k. One operation adds 1 to any single element. You may do at most k operations in total, spread over the elements however you like.
Return the highest number of times one value can appear in the array after your operations.
Example 1
Input: nums = [4, 1, 3, 6], k = 4 Output: 3 Why: raise 3 by 1 and 1 by 3: three 4s
2 more examples and the constraints
Example 2
Input: nums = [2, 9, 5], k = 1 Output: 1 Why: every gap is bigger than 1
Example 3
Input: nums = [7, 7, 2], k = 5 Output: 3 Why: spend all 5 raising 2 to 7
Constraints
- 1 ≤ length of nums ≤ 100,000
- 1 ≤ nums[i] ≤ 100,000
- 1 ≤ k ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort, grow left from each targetO(n²)
- Sort + sliding windowO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers and a large budget | Verdict |
|---|---|---|---|
| Sort, grow left from each target | O(n²) | Right idea, repeated work | |
| Sort + sliding window | O(n log n) | Best; left only moves forward |
n = the length of nums.
Edge cases to test
- One element. [5] gives 1, whatever k is.
- Already equal. [2, 2, 2] costs nothing and gives 3.
- Budget covers everything. [1, 2, 3, 4] with k = 6 makes all four equal to 4.
- No gap is affordable. [2, 9, 5] with k = 1 gives 1.
- Big products. 100,000 × a window of 100,000 overflows a 32-bit int.
Common mistakes
- Trying to lower numbers or picking a target that is not in the array; values only go up, so the target is always an existing number.
- Forgetting to sort, so the cheapest numbers to raise are not next to the target.
- Computing
nums[right] * sizein 32 bits and overflowing.
How to talk through it
- 1Clarify. Can I only add, never subtract? Is k a total across all elements? How large can the values get?
- 2Find the structure. The target is an existing value, and the cheapest numbers to raise are the largest ones below it, so sort.
- 3Give the brute force. For each target, grow left while the cost fits: O(n²) in the worst case.
- 4Slide the window. Keep a running sum; the cost is target × size − sum. Shrink from the left when it passes k.
- 5Test out loud. Run one element, all equal, and a budget that covers everything.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?