Skip to content

Commit 4defdbb

Browse files
authored
Update 1005.K次取反后最大化的数组和.md
与C++相同的思路,不过排序的耗时更长
1 parent e70378f commit 4defdbb

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,33 @@ public:
9999
100100
101101
Java:
102+
```java
103+
class Solution {
104+
public int largestSumAfterKNegations(int[] nums, int K) {
105+
// 将数组按照绝对值大小从大到小排序,注意要按照绝对值的大小
106+
nums = IntStream.of(nums)
107+
.boxed()
108+
.sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
109+
.mapToInt(Integer::intValue).toArray();
110+
int len = nums.length;
111+
for (int i = 0; i < len; i++) {
112+
//从前向后遍历,遇到负数将其变为正数,同时K--
113+
if (nums[i] < 0 && k > 0) {
114+
nums[i] = -nums[i];
115+
k--;
116+
}
117+
}
118+
// 如果K还大于0,那么反复转变数值最小的元素,将K用完
119+
if (k % 2 == 1) nums[len - 1] = -nums[len - 1];
120+
int result = 0;
121+
for (int a : nums) {
122+
result += a;
123+
}
124+
return result;
125+
}
126+
}
127+
```
128+
102129
```java
103130
class Solution {
104131
public int largestSumAfterKNegations(int[] A, int K) {

0 commit comments

Comments
 (0)