510. Sum of Mutated Array Closest to Target

MediumBinary SearchBinary Search on AnswerArray

Given an array and a target, choose an integer value v and replace every element greater than v with v (smaller elements are unchanged). Return the value v that makes the resulting array sum as close as possible to the target. If two values are equally close, return the smaller value. Input: '[arr], target'.

Input: '[arr], target'.

Output: Integer — the chosen value v.

Examples

Example 1
Input: [4,9,3], 10
Output: 3
Explanation: With v=3 sum is 3+3+3=9, closest to 10.
Example 2
Input: [2,3,5], 10
Output: 5
Explanation: No capping needed.
Example 3
Input: [60864,25176,27249,21296,20204], 56803
Output: 11361
Explanation: Closest capped sum.

Constraints

Asked by

GoogleBloomberg
Solve this problem in the editor →