# Minimum Subsequence in Non-Increasing Order
**Difficulty:** EASY
[External](https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order)
Canonical: https://scaleengineer.com/dsa/problems/minimum-subsequence-in-non-increasing-order
**Patterns:** [Greedy](https://scaleengineer.com/dsa/patterns/greedy)
**Algorithms:** [Sorting](https://scaleengineer.com/algorithms/sorting)
**Data structures:** Array
**Companies:** [Mercari](https://scaleengineer.com/companies/mercari)
---
## Problem
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 <= 500`
* `1 <= nums[i] <= 100`

# Approaches
## Brute-Force by Generating All Subsequences
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.
**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.
**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.
### Explanation
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.
### Algorithm
*   Generate all 2^N - 1 non-empty subsequences of the `nums` array.
*   Calculate the `totalSum` of the `nums` array.
*   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.
*   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.

## Greedy Approach with General Sorting
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.
**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.
**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.
### Explanation
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.

```java
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;
    }
}
```
### Algorithm
*   Calculate the sum of all elements in the array, `totalSum`.
*   Sort the input array `nums` in non-increasing (descending) order.
*   Initialize an empty list `subsequence` and a sum `subsequenceSum = 0`.
*   Iterate through the sorted array from the largest element.
*   Add the current element to `subsequence` and `subsequenceSum`.
*   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.

## Optimized Greedy Approach using Counting Sort
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).
**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).
**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.
### Explanation
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.

```java
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
    }
}
```
### Algorithm
*   Define a constant `MAX_VAL = 100`.
*   Create a frequency array, `counts`, of size `MAX_VAL + 1`.
*   Iterate through `nums` to populate `counts` and calculate `totalSum`.
*   Initialize an empty list `subsequence` and a sum `subsequenceSum = 0`.
*   Iterate from `i = MAX_VAL` down to 1.
*   For each number `i`, while its count in `counts` is positive:
    *   Add `i` to `subsequence` and `subsequenceSum`.
    *   Decrement the count of `i`.
    *   If `subsequenceSum > totalSum - subsequenceSum`, the solution is found. Return `subsequence`.

# Solutions
### Java

```java
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;
  }
}

```

### CPP

```cpp
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;
  }
};

```

### Python

```python
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 ans

```
