mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 1005.K次取反后最大化的数组和.md
与C++相同的思路,不过排序的耗时更长
This commit is contained in:
@ -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) {
|
||||
|
Reference in New Issue
Block a user