zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    Django~1
    Python 正则表达式入门(初级篇)
    pytho占位符
    django之基于cookie和装饰器实现用户认证
    form error
    Python之路【第十七篇】:Django【进阶篇 】
    djangoform详解
    django自定义form验证error
    Django CRM客户关系管理系统
    ulimit
  • 原文地址:https://www.cnblogs.com/seyjs/p/10508794.html
Copyright © 2011-2022 走看看