LeetCode1005.Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)

1005.Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)

Description

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.


给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次。(我们可以多次选择同一个索引 i。)

以这种方式修改数组后,返回数组可能的最大和。

题目链接:https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/

个人主页:http://redtongue.cn or https://redtongue.github.io/

Difficulty: easy

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、K小于负数的个数,翻转最小的K个负数;
  • 2、K大于负数的个数,且K-负数的个数等于偶数,翻转所有负数;
  • 3、K大于负数的个数,且K-负数的个数等于奇数,翻转所有负数;
  • 对于1,2返回翻转之后数组的和,对于3,返回翻转之后数组的和减去数组中最小数字的两倍。

参考代码

class Solution(object):
def largestSumAfterKNegations(self, A, K):
    A.sort()
    judge=True
    for i in range(K):
        if(A[i]<0):
            A[i]=-A[i]
        else:
            if((K-i)%2==0):
                judge=True
            else:
                judge=False
            break
    if(judge):
        return sum(A)
    else:
        return sum(A)-2*min(A)

猜你喜欢

转载自blog.csdn.net/redtongue/article/details/88376795