Minimum Subsequence in Non-Increasing Order
EasyPrompt
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
Approaches
3 approaches with complexity analysis and trade-offs.
This naive approach involves generating every possible non-empty subsequence of the input array. For each subsequence, we check if its sum is strictly greater than the sum of the elements not included. Among all such valid subsequences, we find the one that first minimizes the size, and then maximizes the sum. This method is exhaustive but computationally very expensive.
Algorithm
- Generate all 2^N - 1 non-empty subsequences of the
numsarray. - Calculate the
totalSumof thenumsarray. - Create a list to store valid candidate subsequences.
- For each generated subsequence:
- Calculate its sum,
subsequenceSum. - If
subsequenceSum > totalSum - subsequenceSum, add it to the list of candidates.
- Calculate its sum,
- Sort the candidates first by size (ascending) and then by sum (descending).
- The first subsequence in the sorted list is the answer.
- Sort this final subsequence in non-increasing order before returning.
Walkthrough
The core idea is to test every single possibility. We can use a recursive backtracking function or bit manipulation to generate all subsequences. For an array of size N, there are 2^N subsequences. For each one, we compute its sum and the sum of the remaining elements to check the condition. We store all subsequences that satisfy subsequence_sum > remaining_sum. Finally, we iterate through these valid subsequences to find the one with the minimum size. If there's a tie in size, we pick the one with the largest sum. Due to its exponential complexity, this approach is not feasible for the given constraints but serves as a foundational, albeit impractical, solution.
Complexity
Time
O(N * 2^N), where N is the number of elements in `nums`. Generating 2^N subsequences and processing each one takes O(N) time.
Space
O(N * 2^N), required to store all possible subsequences for processing.
Trade-offs
Pros
Guarantees finding the correct solution by checking every possibility.
Conceptually straightforward.
Cons
Extremely inefficient and will result in a 'Time Limit Exceeded' error for the given constraints.
Requires a large amount of memory.
A far more efficient solution uses a greedy strategy. The goal is to find a subsequence with a sum greater than half the total sum, using the minimum number of elements, and then maximizing that sum. To achieve a large sum with the fewest elements, it's always optimal to pick the largest numbers first. This leads to a simple algorithm: sort the array in descending order and add elements to our subsequence one by one until the condition is met.
Algorithm
- Calculate the sum of all elements in the array,
totalSum. - Sort the input array
numsin non-increasing (descending) order. - Initialize an empty list
subsequenceand a sumsubsequenceSum = 0. - Iterate through the sorted array from the largest element.
- Add the current element to
subsequenceandsubsequenceSum. - Check if
subsequenceSum > totalSum - subsequenceSum. - If the condition is met, return the
subsequence. It is guaranteed to be the correct answer and is already sorted.
Walkthrough
This approach hinges on the insight that to satisfy subsequenceSum > totalSum / 2 with the minimum number of elements, we must accumulate sum as quickly as possible. This is achieved by adding the largest elements from the array first. Sorting the array allows us to easily access these largest elements. By iterating through the sorted array and building our subsequence, we ensure that at any given size k, our subsequence has the maximum possible sum. Therefore, the first time our subsequence's sum exceeds half the total sum, we have found the solution with the minimum size and maximum sum for that size. The result is already in the required non-increasing order.
import java.util.ArrayList;import java.util.Arrays;import java.util.List; class Solution { public List<Integer> minSubsequence(int[] nums) { int totalSum = 0; for (int num : nums) { totalSum += num; } // Sort the array in ascending order Arrays.sort(nums); List<Integer> result = new ArrayList<>(); int subsequenceSum = 0; // Iterate from the end (largest elements) for (int i = nums.length - 1; i >= 0; i--) { int currentNum = nums[i]; subsequenceSum += currentNum; result.add(currentNum); int remainingSum = totalSum - subsequenceSum; if (subsequenceSum > remainingSum) { break; } } return result; }}Complexity
Time
O(N log N), dominated by the sorting step. The rest of the operations take O(N) time.
Space
O(N) or O(log N), depending on the space complexity of the sorting algorithm used. The result list also requires up to O(N) space.
Trade-offs
Pros
Vastly more efficient than the brute-force approach.
Relatively simple to implement.
The greedy choice is proven to be optimal for this problem's constraints.
Cons
The O(N log N) sort can be a bottleneck if N is very large, although it's efficient enough for the given constraints.
Can be further optimized if the range of numbers is small.
This approach builds upon the greedy strategy but optimizes the sorting step. Given the constraint that numbers in the array are between 1 and 100, we can use a linear-time sorting algorithm like Counting Sort instead of a comparison-based sort (like Quicksort or Mergesort). This improves the overall time complexity from O(N log N) to O(N).
Algorithm
- Define a constant
MAX_VAL = 100. - Create a frequency array,
counts, of sizeMAX_VAL + 1. - Iterate through
numsto populatecountsand calculatetotalSum. - Initialize an empty list
subsequenceand a sumsubsequenceSum = 0. - Iterate from
i = MAX_VALdown to 1. - For each number
i, while its count incountsis positive:- Add
itosubsequenceandsubsequenceSum. - Decrement the count of
i. - If
subsequenceSum > totalSum - subsequenceSum, the solution is found. Returnsubsequence.
- Add
Walkthrough
The logic is identical to the previous greedy approach, but the implementation is more efficient. We avoid a general sort by using a frequency array (or hash map) to count the occurrences of each number. This takes O(N) time. Then, we iterate from the maximum possible value (100) down to 1. For each value, we add it to our result subsequence as many times as it appeared in the original array, updating the sum and checking the condition after each addition. This effectively processes the numbers in descending order without an explicit O(N log N) sort, leading to a linear time solution.
import java.util.ArrayList;import java.util.List; class Solution { public List<Integer> minSubsequence(int[] nums) { // The range of numbers is 1 to 100 int[] counts = new int[101]; int totalSum = 0; // Populate the frequency map and calculate total sum for (int num : nums) { counts[num]++; totalSum += num; } List<Integer> result = new ArrayList<>(); int subsequenceSum = 0; // Iterate from the largest possible number down to the smallest for (int i = 100; i >= 1; i--) { while (counts[i] > 0) { subsequenceSum += i; result.add(i); counts[i]--; if (subsequenceSum > totalSum - subsequenceSum) { return result; } } } return result; // Should not be reached }}Complexity
Time
O(N + M), where N is the number of elements and M is the range of possible values (100). Since M is a small constant, the complexity simplifies to O(N).
Space
O(M + k), where M is the range of values (O(1) space for the `counts` array) and k is the size of the result subsequence (O(N) in the worst case). The total space is O(N).
Trade-offs
Pros
Optimal time complexity for this problem.
Most efficient solution due to linear time processing.
Cons
This optimization is specific to problems where the range of input values is small and bounded.
Solutions
Solution
class Solution {public List<Integer> minSubsequence(int[] nums) { Arrays.sort(nums); List<Integer> ans = new ArrayList<>(); int s = Arrays.stream(nums).sum(); int t = 0; for (int i = nums.length - 1; i >= 0; i--) { t += nums[i]; ans.add(nums[i]); if (t > s - t) { break; } } return ans; }}class Solution {public: vector<int> minSubsequence(vector<int> &nums) { sort(nums.rbegin(), nums.rend()); int s = accumulate(nums.begin(), nums.end(), 0); int t = 0; vector<int> ans; for (int x : nums) { t += x; ans.push_back(x); if (t > s - t) { break; } } return ans; }};class Solution: def minSubsequence(self, nums: List[int]) -> List[int]: ans = [] s, t = sum(nums), 0 for x in sorted(nums, reverse=True): t += x ans . append(x) if t > s - t: break return ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.