Update1005.K次取反后最大化的数组和,添加C#

This commit is contained in:
eeee0717
2023-12-31 09:35:51 +08:00
parent a66e5e39ba
commit 85f8efeef6

View File

@ -322,6 +322,29 @@ object Solution {
}
```
### C#
```csharp
public class Solution
{
public int LargestSumAfterKNegations(int[] nums, int k)
{
int res = 0;
Array.Sort(nums, (a, b) => Math.Abs(b) - Math.Abs(a));
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] < 0 && k > 0)
{
nums[i] *= -1;
k--;
}
}
if (k % 2 == 1) nums[nums.Length - 1] *= -1;
foreach (var item in nums) res += item;
return res;
}
}
```
<p align="center">