【leetcode】1005. 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. 1 <= A.length <= 10000
  2. 1 <= K <= 10000
  3. -100 <= A[i] <= 100

解题思路:把A按升序排序,如果存在负数,那么优先把较大的负数变成正数,直到K次变换用换为止。如果K大于负数的个数,这时A中已经全部是正数了,我们知道对一个数变换两次相当于不做变换,因此只要判断剩余的可变换次数是奇数还是偶数。如果是偶数,那表示不用再做变换;如果是奇数,则把A中最小的正数做变换。最后求出A的总和即可。

代码如下:

class Solution(object):
    def largestSumAfterKNegations(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        A.sort()
        res = 0
        lastMin = 10001
        for i in A:
            if K == 0:
                res += i
            elif i < 0:
                res += (-i)
                K -= 1
                lastMin = min(lastMin,-i)
            else:
                K = K%2
                if K == 1:
                    if lastMin < i:
                        res -= 2*lastMin
                        res += i
                    else:
                        res -= i
                    K = 0
                else:
                    res += i
        return res

 

posted @ 2019-03-11 09:46  seyjs  阅读(271)  评论(0)    收藏  举报