用 Python 购买汽车

pythonserver side programmingprogramming更新于 2025/11/3 20:28:17

假设我们有一份待售汽车价格清单,并且预算为 k,我们必须找到可以购买的最大汽车数量。

因此,如果输入为 [80, 20, 10, 30, 80],k = 85,则输出将为 3,因为我们可以购买三辆价格分别为 20、10、40 的汽车

为了解决这个问题,我们将遵循以下步骤 −

  • count := 0

  • 对列表价格进行排序

  • 对于 i,范围为 0 到价格大小,执行

    • 如果 prices[i] <=k,则

      • k := k-prices[i]

      • count := count + 1

    • 否则,

      • 退出循环

  • 返回 count

让我们看看下面的实现以便更好地理解 −

示例

class Solution:
   def solve(self, prices, k):
      count =0
      prices.sort()
      for i in range(len(prices)):
         if(prices[i]<=k):
            k = k-prices[i]
            count += 1
         else:
            break
      return count
ob = Solution()
p = [80, 20, 10, 30, 80]
print(ob.solve(p, 85))

输入

[80, 20, 10, 30, 80], 85

输出

3

相关文章


有用资源