Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd4e98f4

Browse files
Merge pull requestyoungyangyang04#498 from daniel1n/patch-6
Update 1005.K次取反后最大化的数组和.md
2 parents5147710 +4defdbb commitd4e98f4

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
classSolution {
104131
publicintlargestSumAfterKNegations(int[]A,intK) {

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp