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

Commit 9072299

Browse files
author
Shuo
authored
Merge pull request #471 from openset/develop
Add: Maximize Sum Of Array After K Negations
2 parents 7988ff3 + 9432088 commit 9072299

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package maximize_sum_of_array_after_k_negations
2+
3+
import "sort"
4+
5+
func largestSumAfterKNegations(A []int, K int) int {
6+
sort.Ints(A)
7+
ans, min := 0, A[len(A)-1]
8+
for _, v := range A {
9+
if K > 0 && v <= 0 {
10+
K, v = K-1, -v
11+
}
12+
if v < min {
13+
min = v
14+
}
15+
ans += v
16+
}
17+
if K&1 == 1 {
18+
ans -= min * 2
19+
}
20+
return ans
21+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package maximize_sum_of_array_after_k_negations
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
k int
8+
expected int
9+
}
10+
11+
func TestLargestSumAfterKNegations(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
input: []int{4, 2, 3},
15+
k: 1,
16+
expected: 5,
17+
},
18+
{
19+
input: []int{3, -1, 0, 2},
20+
k: 3,
21+
expected: 6,
22+
},
23+
{
24+
input: []int{2, -3, -1, 5, -4},
25+
k: 2,
26+
expected: 13,
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := largestSumAfterKNegations(tc.input, tc.k)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /