1403. Minimum Subsequence in Non-Increasing Order*

1403. Minimum Subsequence in Non-Increasing Order*

https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/

题目描述

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

C++ 实现 1

看例子就能发现, 思路是将数组从大到小排序, 如果 sum(nums[0, ..., i]) 能大于 nums 剩下的元素之和, 返回 nums[0, ..., i] 即可.

class Solution {
public:
    vector<int> minSubsequence(vector<int>& nums) {
        auto sum = std::accumulate(nums.begin(), nums.end(), 0);
        std::sort(nums.rbegin(), nums.rend()); // greater -> smaller
        vector<int> res;
        int val = 0;
        for (int i = 0; i < nums.size(); ++ i) {
            val += nums[i];
            res.push_back(nums[i]);
            if (val > sum - val) break;
        }
        return res;
    }
};
发布了497 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/105570670