mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
Update1005.K次取反后最大化的数组和,添加C#
This commit is contained in:
@ -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">
|
<p align="center">
|
||||||
|
Reference in New Issue
Block a user