[leetcode] 1403. Minimum Subsequence in Non-Increasing Order

网友投稿 1060 2022-08-23

[leetcode] 1403. Minimum subsequence in Non-Increasing Order

[leetcode] 1403. Minimum Subsequence in Non-Increasing Order

Description

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 <= 5001 <= nums[i] <= 100

分析

题目的意思是:给定一个数字序列,找出一个子序列的和比剩下序列的和大的序列。找出符合条件的最小子序列。

贪心法,对数组进行排序,从后往前找,先找大的数,用cur记录遍历的和,res记录遍历的值,当cur第一次大于数组的总和total的时候,说明找到了一个符合条件的res。

代码

class Solution {public: int distributeCandies(vector& candies) { unordered_set s; int cnt=0; for(int candy:candies){ s.insert(candy); cnt++; } return min((int)s.size(),cnt/2); }};

参考文献

​​【LeetCode】1403. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:mac vlc-qt编译安装教程
下一篇:QT5 mac QtXlsxWriter的使用
相关文章

 发表评论

暂时没有评论,来抢沙发吧~