leetcode 1403. Minimum Subsequence in Non-Increasing Order(python)

274 阅读1分钟

描述

Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.

If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.

Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.

Example 1:

Input: nums = [4,3,10,9,8]
Output: [10,9] 
Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements. 	

Example 2:

Input: nums = [4,4,7,6,7]
Output: [7,7,6] 
Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to returned in non-decreasing order.  

Example 3:

Input: nums = [6]
Output: [6]

Note:

1 <= nums.length <= 500
1 <= nums[i] <= 100

解析

根据题意,要找出最短的且和是最大的子序列,并且该子序列的和大于其他元素之和,只需要将 nums 排序,然后从最大的值开始从大到小遍历 nums[i] ,如果 res 的和没有 nums 其余元素的和大,则将 nums[i] 追加到 res 中,遍历结束即可得到答案 res 。

解答

class Solution(object):
    def minSubsequence(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        nums.sort()
        res = [nums.pop()]
        while sum(res) <= sum(nums):
            res.append(nums.pop())
        return res
        	      
		

运行结果

Runtime: 56 ms, faster than 55.70% of Python online submissions for Minimum Subsequence in Non-Increasing Order.
Memory Usage: 13.4 MB, less than 62.03% of Python online submissions for Minimum Subsequence in Non-Increasing Order.

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

您的支持是我最大的动力