Minimum Subsequence in Non-Increasing Order Problem
Description
LeetCode Problem 1403.
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 be returned in non-increasing order.
Constraints:
1 <= nums.length <= 5001 <= nums[i] <= 100
Solution
Approach: Greedy, Largest Elements First
To make the chosen sum larger than the rest using as few elements as possible, the elements we choose should be as large as possible. So sort nums in decreasing order and take elements from the front until the taken sum is strictly greater than the sum of the rest.
Why this is optimal: if any k elements can beat the rest, then the k largest elements can too, because they have the largest possible sum among k elements (and so the rest has the smallest one). So the greedy prefix has the minimum size. Among all choices of that size, the k largest elements also have the maximum total sum, which settles the tie-break. It is also already in non-increasing order, as the answer must be.
Keep rest, the sum of the elements not yet taken, starting from the total; after taking x, add it to taken, subtract it from rest and stop once taken > rest. The comparison is strict: in Example 2, [7,7] sums to 14, which only ties the remaining 4 + 4 + 6, so we must also take the 6.
Complexity: O(n log n) time for sorting and O(n) space for the answer.
class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
rest = sum(nums) # sum of the elements not taken yet
taken = 0
ans = []
for x in sorted(nums, reverse=True): # the largest elements first
ans.append(x)
taken += x
rest -= x
if taken > rest:
break
return ans