← MathWorks Interview Insights
Binary search on the answer is the move here, but I didn't see it immediately.
First, recognize that the problem is to find the maximum possible minimum value after exactly K decrements. Use binary search on the answer: for a candidate minimum X, compute the total decrements needed to make all elements at least X (i.e., sum of max(0, X - a[i])). If this sum ≤ K, then X is feasible. The answer is the largest feasible X.
Pro tip: Clarify that after making all elements at least X, any remaining decrements can be applied to any element without reducing the minimum below X, as long as we don't drop below X. This ensures exactly K operations are used.
Restate the goal: after exactly K decrements, maximize the minimum element. Note that decrements can only reduce values, so the minimum cannot increase.
For a target minimum X, compute the total decrements needed to raise all elements to at least X: sum(max(0, X - a[i])). If this sum ≤ K, X is achievable.
Binary search X between the current minimum and the maximum possible value (e.g., max(a) + K). Find the largest X for which the feasibility check holds.
After ensuring all elements ≥ X, if there are leftover decrements, apply them to any element(s) without dropping below X. This is always possible if X is feasible.
The binary search runs in O(n log(maxVal + K)) time, which is efficient for typical constraints.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.