-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution1005.java
62 lines (55 loc) · 1.72 KB
/
Solution1005.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
58
59
60
61
62
package leetcode.binarysearch;
import java.util.Arrays;
public class Solution1005 {
public static void main(String[] args) {
System.out.println(new Solution1005().largestSumAfterKNegations(new int[]{-4,-2,-3}, 4));
}
public int largestSumAfterKNegations(int[] nums, int k) {
Arrays.sort(nums);
int left = 0, right = nums.length;
while (left < right) {
int mid = left + right >> 1;
if (nums[mid] >= 0) {
right = mid;
} else {
left = mid + 1;
}
}
int res = 0;
if (left > 0) { // 有负数
if (left >= k) {
for (int num : nums) {
if (k > 0) {
res -= num;
k--;
} else {
res += num;
}
}
} else {
// 负数太少了
for (int num : nums) {
if (num < 0) {
res -= num;
} else {
res += num;
}
}
k -= left;
if (left == nums.length && k % 2 != 0) {
res += 2 * nums[left - 1];
} else if (left < nums.length && nums[left] != 0 && k % 2 != 0) {
res -= 2 * Math.min(nums[left], Math.abs(nums[left - 1]));
}
}
} else { // 没有负数
for (int num : nums) {
res += num;
}
if (k % 2 != 0 && nums[left] != 0) {
res -= 2 * nums[left];
}
}
return res;
}
}