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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

➤微信公众号:山青咏芝(let_us_code)

➤个人域名:https://www.zengqiang.org

➤GitHub地址:https://github.com/strengthen/LeetCode

➤原文地址:

➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。

➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 }