-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1005-MaximizeSumOfArrayAfterKNegations.cs
46 lines (40 loc) · 1.22 KB
/
1005-MaximizeSumOfArrayAfterKNegations.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//-----------------------------------------------------------------------------
// Runtime: 96ms
// Memory Usage: 25.2 MB
// Link: https://leetcode.com/submissions/detail/344226744/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _1005_MaximizeSumOfArrayAfterKNegations
{
public int LargestSumAfterKNegations(int[] A, int K)
{
var list = new SortedList<int, int>(A.Length);
var sum = 0;
foreach (var num in A)
{
if (!list.ContainsKey(num))
list.Add(num, 1);
else
list[num]++;
sum += num;
}
for (int i = 0; i < K; i++)
{
var num = list.First().Key;
if (num == 0) break;
sum -= num * 2;
list[num]--;
if (list[num] == 0)
list.Remove(num);
if (!list.ContainsKey(-num))
list.Add(-num, 1);
else
list[-num]++;
}
return sum;
}
}
}