【leetcode】1005. Maximize Sum Of Array After K Negations

本文探讨了一种算法问题,即如何通过K次取反操作使整数数组达到最大可能的和。首先对数组进行升序排序,优先转换最大的负数为正数,然后根据剩余的K值决定是否需要进一步转换最小的正数。

题目如下:

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

 

转载于:https://www.cnblogs.com/seyjs/p/10508794.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值