describe
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: And [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.Copy the code
Example 2:
Input: nums = [4,4,7,6] 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-stress order.Copy the code
Example 3:
Input: nums = [6]
Output: [6]
Copy the code
Note:
1 <= nums.length <= 500
1 <= nums[i] <= 100
Copy the code
parsing
To find the shortest subsequence whose sum is the largest and whose sum is greater than the sum of the other elements, sort nums and traverse nums[I] from the largest to the smallest. If the sum of res is not as large as the sum of the rest of nums, Nums [I] is appended to res, and the answer res is obtained at the end of the traversal.
answer
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
Copy the code
The results
Runtime: 56 MS, faster than 55.70% of Python online submissions for Minimum Subsequence in non-increasing Order. Memory Usage: Submissions in Python online submissions for Minimum Subsequence in non-increasing Order.Copy the code
Original link: leetcode.com/problems/mi…
Your support is my biggest motivation