-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1005.k-次取反后最大化的数组和.java
46 lines (37 loc) · 1.09 KB
/
1005.k-次取反后最大化的数组和.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
/*
* @lc app=leetcode.cn id=1005 lang=java
*
* [1005] K 次取反后最大化的数组和
*/
// @lc code=start
import java.util.Arrays;
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Arrays.sort(nums);
int i = 0;
int maxSum = 0;
// step 1, flip all negative value, or run out of k
while (k > 0 && i < nums.length && nums[i] < 0) {
nums[i] = -nums[i];
maxSum += nums[i];
k--;
i++;
}
// step 2, if really run out of k, just add left elements.
// Or if all elements are positive now and still have k,
// pick the minimium value and process, then add left elements.
// so, add left elements can move out of Cond.
if (k != 0) {
int minValue = Arrays.stream(nums).summaryStatistics().getMin();
if (k % 2 == 1) {
maxSum -= 2 * minValue;
}
}
while (i < nums.length) {
maxSum += nums[i];
i++;
}
return maxSum;
}
}
// @lc code=end