# 1005. Maximize Sum Of Array After K Negations

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/

> 内容描述

```
Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total.  (We may choose the same index i multiple times.)

Return the largest possible sum of the array after modifying it in this way.

 

Example 1:

Input: A = [4,2,3], K = 1
Output: 5
Explanation: Choose indices (1,) and A becomes [4,-2,3].
Example 2:

Input: A = [3,-1,0,2], K = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].
Example 3:

Input: A = [2,-3,-1,5,-4], K = 2
Output: 13
Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].
 

Note:

1 <= A.length <= 10000
1 <= K <= 10000
-100 <= A[i] <= 100
```

## 解题方案

> 思路 1
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(N)******



开始考虑了很多情况，代码很丑

```python
class Solution:
    def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
        flag = False
        if 0 in A:
            flag = True
        if flag:
            neg, pos = sorted([i for i in A if i < 0]), sorted([i for i in A if i > 0])
            tmp = min(K, len(neg))
            sums = -sum(neg[:tmp]) + sum(neg[tmp:]) + sum(pos)
            return sums
        else:
            neg, pos = sorted([i for i in A if i < 0]), sorted([i for i in A if i > 0])
            if K <= len(neg):
                tmp = K
                return -sum(neg[:tmp]) + sum(neg[tmp:]) + sum(pos)
            else:
                tmp = len(neg)
                if (K - tmp) % 2 == 0:
                    return -sum(neg[:tmp]) + sum(neg[tmp:]) + sum(pos)
                else:
                    sums = -sum(neg[:tmp]) + sum(neg[tmp:]) + sum(pos)
                    if tmp > 0:
                        maxs = max(2 * neg[tmp-1], -2*pos[0])
                        sums += maxs
                    else:
                        sums += -2 * pos[0]
                    return sums
```


> 思路 2
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(1)******

照抄[[C++/Python] Sort](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/252254/C%2B%2BPython-Sort)

```python
class Solution:
    def largestSumAfterKNegations(self, A: List[int], K: int) -> int:  
        A.sort()
        i = 0
        while i < len(A) and i < K and A[i] < 0:
            A[i] = -A[i]
            i += 1
        return sum(A) - ((K - i) % 2) * (2 * min(A))
```



















