Minimum Subsequence in Non-Increasing Order - Greedy - Easy - LeetCode
💻 coding

Minimum Subsequence in Non-Increasing Order - Greedy - Easy - LeetCode

1 min read 268 words
1 min read
ShareWhatsAppPost on X
  • 1The goal is to find a subsequence whose sum is strictly greater than the sum of non-included elements.
  • 2If multiple subsequences meet the criteria, the solution should have the minimum size and maximum total sum.
  • 3The resulting subsequence must be returned in non-increasing order.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The goal is to find a subsequence whose sum is strictly greater than the sum of non-included elements."

Minimum Subsequence in Non-Increasing Order - Greedy - Easy - LeetCode

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 returned in non-decreasing order. Example 3:

Input: nums = [6] Output: [6]

Constraints:

1 <= nums.length <= 500 1 <= nums[i] <= 100

public class Solution {
 public IList<int> MinSubsequence(int[] nums) {
 Array.Sort(nums);
 int sum = 0;
 for(int i=0;i<nums.Length;i++){
 sum+=nums[i]; 
 }
 
 int halfSum = sum/2;
 sum = 0;
 var res = new List<int>(); 
 for(int i=nums.Length-1;i>=0 && sum <= halfSum;i--){
 sum+=nums[i];
 res.Add(nums[i]);
 }
 
 return res;
 }
}

Time Complexity: O(nlogn)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 5 October 2020 · 1 min read · 268 words

Part of AskGif Blog · coding

You might also like