Given an integer array arr and a target value target, you need to find an integer value such that when you replace all integers in the array greater than value with value, the sum of the resulting array is as close to target as possible. If there are multiple such integers, return the minimum one.
This is a high-quality Medium problem frequently asked by Google and Bloomberg. it tests the ability to recognize a monotonic property (as value increases, the sum increases) which allows for Binary Search. It also evaluates a candidate's attention to detail, specifically in handling the "closest" condition where you must compare two potential candidates (one slightly below and one slightly above the ideal sum).
The pattern is "Binary Search on the Result Space."
The possible range for value is between 0 and the maximum element in the array.
value.value.arr = [4, 9, 3], target = 10.
value = 3: Array becomes [3, 3, 3]. Sum = 9. Difference = |9 - 10| = 1.value = 4: Array becomes [4, 4, 3]. Sum = 11. Difference = |11 - 10| = 1.
Since both have the same difference, we return the smaller value, which is 3.value in O(log N) instead of O(N).Binary search isn't just for searching elements in an array; it's also for finding an optimal value in a defined range. If a function is monotonic (always increasing or always decreasing), you can use binary search to find a target value.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Right Interval | Medium | Solve | |
| Most Beautiful Item for Each Query | Medium | Solve | |
| Magnetic Force Between Two Balls | Medium | Solve | |
| Special Array With X Elements Greater Than or Equal X | Easy | Solve | |
| Find Target Indices After Sorting Array | Easy | Solve |