[LeetCode]#1403. Minimum Subsequence in Non-Increasing Order
Environment: Python 3.7
Key technique: sort, append
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.
Analysis:
- Sort it .
- Sum it as sum_n (34).
- Sum nums[i] as total from maximum to minimal number and add it to list.
- If (sum_n-total)<total : break
- Get answer.
Solution:
class Solution:
def minSubsequence(self, nums):
nums.sort(reverse=True)
sum_n=sum(nums)
l=len(nums)
total=0
ans=[]
for i in nums:
total+=i
ans.append(i)
if (sum_n-total)<total:
break
return ans
Submissions: