Update 1005.K次取反后最大化的数组和.md

与C++相同的思路,不过排序的耗时更长
This commit is contained in:
daniel1n
2021-07-17 22:45:14 +08:00
committed by GitHub
parent e70378fc62
commit 4defdbba77

View File

@ -99,6 +99,33 @@ public:
Java
```java
class Solution {
public int largestSumAfterKNegations(int[] nums, int K) {
// 将数组按照绝对值大小从大到小排序,注意要按照绝对值的大小
nums = IntStream.of(nums)
.boxed()
.sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
.mapToInt(Integer::intValue).toArray();
int len = nums.length;
for (int i = 0; i < len; i++) {
//从前向后遍历遇到负数将其变为正数同时K--
if (nums[i] < 0 && k > 0) {
nums[i] = -nums[i];
k--;
}
}
// 如果K还大于0那么反复转变数值最小的元素将K用完
if (k % 2 == 1) nums[len - 1] = -nums[len - 1];
int result = 0;
for (int a : nums) {
result += a;
}
return result;
}
}
```
```java
class Solution {
public int largestSumAfterKNegations(int[] A, int K) {