• [Swift]LeetCode1196. 最多可以买到的苹果数量 | How Many Apples Can You Put into the Basket


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(let_us_code)
    ➤个人域名:https://www.zengqiang.org
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/11521670.html
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    You have some apples, where arr[i] is the weight of the i-th apple.  You also have a basket that can carry up to 5000 units of weight.

    Return the maximum number of apples you can put in the basket.

    Example 1:

    Input: arr = [100,200,150,1000]
    Output: 4
    Explanation: All 4 apples can be carried by the basket since their sum of weights is 1450.
    

    Example 2:

    Input: arr = [900,950,800,1000,700,800]
    Output: 5
    Explanation: The sum of weights of the 6 apples exceeds 5000 so we choose any 5 of them.
    

    Constraints:

    • 1 <= arr.length <= 10^3
    • 1 <= arr[i] <= 10^3

    楼下水果店正在促销,你打算买些苹果,arr[i] 表示第 i 个苹果的单位重量。

    你有一个购物袋,最多可以装 5000 单位重量的东西,算一算,最多可以往购物袋里装入多少苹果。

    示例 1:

    输入:arr = [100,200,150,1000]
    输出:4
    解释:所有 4 个苹果都可以装进去,因为它们的重量之和为 1450。
    

    示例 2:

    输入:arr = [900,950,800,1000,700,800]
    输出:5
    解释:6 个苹果的总重量超过了 5000,所以我们只能从中任选 5 个。
    

    提示:

    • 1 <= arr.length <= 10^3
    • 1 <= arr[i] <= 10^3

    52ms

     1 class Solution {
     2     func maxNumberOfApples(_ arr: [Int]) -> Int {
     3         var arr = arr
     4         arr.sort()
     5         var cnt:Int = 0
     6         var w:Int = 5000
     7         for a in arr
     8         {
     9             if w >= a
    10             {
    11                 w -= a
    12                 cnt += 1
    13             }
    14             else
    15             {
    16                 break
    17             }
    18         }
    19         return cnt
    20     }
    21 }
  • 相关阅读:
    Redis常见问题及解决方案
    Maven构建报错问题解决
    Nginx正向代理设置
    Linux下限制某程序CPU占用
    Linux-flock文件锁的使用
    Python将print输出内容保存到指定文件中
    使用Zabbix官方模板监控Redis运行状况
    阿里云ossfs配置
    docker swarm 集群及可视化界面的安装及配置
    http://www.fx114.net/qa-24-116329.aspx
  • 原文地址:https://www.cnblogs.com/strengthen/p/11521670.html
Copyright © 2020-2023  润新知