- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1300.java
57 lines (54 loc) · 2.1 KB
/
_1300.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
packagecom.fishercoder.solutions.secondthousand;
publicclass_1300 {
publicstaticclassSolution1 {
publicintfindBestValue(int[] arr, inttarget) {
intave = target / arr.length;
intmax = arr[0];
intmin = arr[0];
for (inti = 1; i < arr.length; i++) {
min = Math.min(min, arr[i]);
max = Math.max(max, arr[i]);
}
if (ave >= max) {
returnmax;
}
// if ave is the best value, what's the difference to target?
intclosetDiff = findClosestDiffIfReplaceWithVal(arr, ave, target);
intbestValue = ave;
// extend candidate towards the right to see how close the sum could be to target
intcandidateOnTheRight = ave;
while (candidateOnTheRight <= max) {
intthisOne = findClosestDiffIfReplaceWithVal(arr, ++candidateOnTheRight, target);
if (thisOne >= closetDiff) {
break;
} else {
closetDiff = thisOne;
bestValue = candidateOnTheRight;
}
}
// extend candidate towards the left to see how close the sum could be to target
intcandidateOnTheLeft = ave;
while (candidateOnTheLeft >= min) {
intthisOne = findClosestDiffIfReplaceWithVal(arr, --candidateOnTheLeft, target);
if (thisOne >= closetDiff) {
break;
} else {
closetDiff = thisOne;
bestValue = candidateOnTheLeft;
}
}
returnbestValue;
}
privateintfindClosestDiffIfReplaceWithVal(int[] arr, intreplaceValue, inttarget) {
intsum = 0;
for (inti = 0; i < arr.length; i++) {
if (arr[i] > replaceValue) {
sum += replaceValue;
} else {
sum += arr[i];
}
}
returnMath.abs(sum - target);
}
}
}