zoukankan      html  css  js  c++  java
  • 【leetcode】1403. 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

    解题思路:把nums按降序排序,从最大的优先选起,直到和超过总和的一半为止。

    代码如下:

    class Solution(object):
        def minSubsequence(self, nums):
            """
            :type nums: List[int]
            :rtype: List[int]
            """
            total = sum(nums)
            amount = 0
            res = []
            nums.sort(reverse=True)
            while len(nums) > 0:
                val = nums.pop(0)
                res.append(val)
                total -= val
                amount += val
                if amount > total:break
            return res
  • 相关阅读:
    Shiro【常用的自定义】
    Shiro【重要概念总结】
    Shiro【自定义Realm实战】
    Shiro【内置Realm实操】
    Shiro【快速上手】
    Shiro【初识】
    面向对象【抽象类和接口的区别】
    面向对象【多态中的成员访问特点】
    Kafka2.12-2.5.0在windows环境的安装 启动 通信测试
    CentOS.iso 下载地址收纳整理
  • 原文地址:https://www.cnblogs.com/seyjs/p/12771504.html
Copyright © 2011-2022 走看看