Skip to content

Commit 11c7e20

Browse files
committed
5135. Sum Of Mutated Array Closest To Target V1.0
1 parent 7f6cc97 commit 11c7e20

File tree

1 file changed

+45
-0
lines changed
  • LeetCode/5135. Sum Of Mutated Array Closest To Target/src

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.Arrays;
2+
3+
/**
4+
* @author changleamazing
5+
* @date 2019/12/29 00:49
6+
* source: https://leetcode-cn.com/problems/sum-of-mutated-array-closest-to-target/submissions/
7+
**/
8+
public class Solution {
9+
10+
public int findBestValue(int[] arr, int target) {
11+
int[] newArr = new int[arr.length + 1];
12+
System.arraycopy(arr, 0, newArr, 1, arr.length);
13+
Arrays.sort(newArr);
14+
int length = newArr.length;
15+
16+
// 如果总和比 target 还小,则不需要替换。
17+
if (Arrays.stream(newArr).sum() <= target) {
18+
return newArr[length - 1];
19+
}
20+
// 已经遍历过的数字的和
21+
int sum = 0;
22+
// 剩下的数字个数
23+
int leftNum;
24+
// 剩下的数字和达到 target 需要的平均数
25+
double leftAverage;
26+
for (int i = 0; i < length - 1; i++) {
27+
sum += newArr[i];
28+
leftNum = length - i - 1;
29+
leftAverage = (target - sum) / (double) leftNum;
30+
// 如果平均数比下一个数小,则说明后面的数都要被替换
31+
if (leftAverage <= newArr[i + 1]) {
32+
// 如果 leftAverage <= x.5 ,则取 Math.floor(leftAverage);否则相反
33+
return (int) (leftAverage - Math.floor(leftAverage) <= 0.5 ? Math.floor(leftAverage)
34+
: Math.ceil(leftAverage));
35+
}
36+
}
37+
return target - sum;
38+
}
39+
40+
public static void main(String[] args) {
41+
int[] arr = {20693, 79539, 84645, 66727, 81334, 185, 14263, 53984, 71844, 71546};
42+
new Solution().findBestValue(arr, 39947);
43+
44+
}
45+
}

0 commit comments

Comments
 (0)