Given the array nums
, obtain a subsequence of the array such that the sum of its elements is strict greater than the sum of the non-included elements. If there are multiple solutions, return the subsequence with the minimum length and if there still are multiple solutions, return the subsequence with the maximum total sum. The result should be in non-increasing order.
nums
?
nums
contain duplicate values?
nums
can contain duplicate values.nums
in descending order.def minSubsequence(nums):
nums.sort(reverse=True) # Sort in non-increasing order
total_sum = sum(nums)
subsequence_sum = 0
subsequence = []
for num in nums:
subsequence_sum += num
subsequence.append(num)
if subsequence_sum > total_sum - subsequence_sum:
return subsequence
# Example usage
nums = [4, 3, 10, 9, 8]
print(minSubsequence(nums)) # Output should be: [10, 9]
Thus, the overall time complexity is O(n log n) due to the sorting step.
This solution ensures that we find the smallest subsequence in non-increasing order such that it has a sum greater than the remaining elements. The sorting guarantees that we always consider larger elements first, which helps in finding the minimal length subsequence effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?