leetcode 1005. Maximize Sum Of Array After K Negations(python)

386 阅读1分钟

这是我参与更文挑战的第26天,活动详情查看: 更文挑战

描述

Given an array nums of integers, we must modify the array in the following way: we choose an i and replace nums[i] with -nums[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: nums = [4,2,3], k = 1
Output: 5
Explanation: Choose indices (1,) and nums becomes [4,-2,3].	

Example 2:

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

Example 3:

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

Note:

1 <= nums.length <= 10000
1 <= k <= 10000
-100 <= nums[i] <= 100

解析

根据题意,就是执行 k 次操作,该操作就是必须将 nums 中的某个数变为相反数,经过 k 次操作之后求 nums 的和。直接循环 k 次,每次循环在 nums 里面找出相反数为最大的元素,将其改为其相反数,经过 k 轮循环,最后对 nums 求和即可。

解答

class Solution(object):
    def largestSumAfterKNegations(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        while k:
            mx = float("-inf")
            idx = None
            for i,n in enumerate(nums):
                if -n>=mx:
                    mx = -n
                    idx = i
            nums[idx] = -nums[idx]
            k-=1
        return sum(nums)
        	      
		

运行结果

Runtime: 300 ms, faster than 5.56% of Python online submissions for Maximize Sum Of Array After K Negations.
Memory Usage: 13.5 MB, less than 62.50% of Python online submissions for Maximize Sum Of Array After K Negations.

解析

上面的解法好理解,但是效率不高,所以用数据结构中的堆可以更有效,思路和上面一样,每次从堆 nums 中找出最小值,并将其变为相反数,然后更新当前 nums 的和,重复 k 次即可得到答案。

解答

 class Solution(object):
    def largestSumAfterKNegations(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        result = sum(nums)
        heapq.heapify(nums)
        while k:
            mn = heapq.heappop(nums)
            heapq.heappush(nums, -mn)
            result += -mn*2
            k -=1
        return result           	      
		

运行结果

Runtime: 44 ms, faster than 34.72% of Python online submissions for Maximize Sum Of Array After K Negations.
Memory Usage: 13.4 MB, less than 62.50% of Python online submissions for Maximize Sum Of Array After K Negations.	

原题链接:leetcode.com/problems/ma…

您的支持是我最大的动力