# 1300. Sum of Mutated Array Closest to Target ###### tags: `Leetcode` `Binary Search` `Medium` Link: https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/ ## 思路 找到第一个大于target的sum 把它和最大的小于target的sum比较 看哪个离target近 ## Code ```java= class Solution { public int findBestValue(int[] arr, int target) { int start = 0; int end = 0; for(int num:arr){ end = Math.max(end, num); } while(start<end){ int mid = start+(end-start)/2; int newSum = computeNewSum(arr, mid); if(newSum<target){ start = mid+1; } else{ end = mid; } } if(computeNewSum(arr,start)-target<target-computeNewSum(arr,start-1)) return start; else return start-1; } private int computeNewSum(int[] arr, int value){ int sum = 0; for(int num:arr) sum += Math.min(num, value); return sum; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up