Minimum Subsequence in Non-Increasing Order
The problem is asking for a subsequence of the given array nums
such that the sum of the elements in this subsequence is strictly greater than the sum of the elements not in the subsequence. If there are multiple solutions, we want the one with the minimum size and the maximum total sum, and the result should be sorted in non-increasing order.
Approach
- Sort the Array: Sort the given array
nums
in non-increasing order. This ensures that we can construct the subsequence with the minimum size and maximum sum. - Initialize Variables: Initialize a variable
total_sum
to store the sum of all elements in the array. Initialize another variablecurrent_sum
to store the sum of elements in the current subsequence. Settotal_sum
as the sum of all elements innums
andcurrent_sum
to 0. - Iterate and Build Subsequence: Iterate through the sorted array, adding elements to the subsequence until the
current_sum
becomes greater than half of thetotal_sum
. This ensures that the sum of the subsequence is strictly greater than the sum of the remaining elements. - Return Result: Return the subsequence constructed so far.
Code
|
|
Explanation
- Sorting the array ensures that we consider the largest elements first, so we can obtain a subsequence with the minimum size.
- By keeping track of the
current_sum
, we can stop as soon as we have a subsequence whose sum is strictly greater than the sum of the other elements.
Example
For the input nums = [4,3,10,9,8]
, the sorted array will be [10,9,8,4,3]
. The resulting subsequence will be [10,9]
, which has a sum strictly greater than the sum of the remaining elements.
This solution meets the constraints and efficiently computes the required output by sorting the array once and then iterating through it.