天天看点

算法刷题打卡第87天:装满杯子需要的最短总时长装满杯子需要的最短总时长

装满杯子需要的最短总时长

难度:简单

现有一台饮水机,可以制备冷水、温水和热水。每秒钟,可以装满

2

杯 不同 类型的水或者

1

杯任意类型的水。

给你一个下标从

开始、长度为

3

的整数数组

amount

,其中

amount[0]

amount[1]

amount[2]

分别表示需要装满冷水、温水和热水的杯子数量。返回装满所有杯子所需的 最少 秒数。

示例 1:

输入:amount = [1,4,2]
输出:4
解释:下面给出一种方案:
第 1 秒:装满一杯冷水和一杯温水。
第 2 秒:装满一杯温水和一杯热水。
第 3 秒:装满一杯温水和一杯热水。
第 4 秒:装满一杯温水。
可以证明最少需要 4 秒才能装满所有杯子。
           

示例 2:

输入:amount = [5,4,4]
输出:7
解释:下面给出一种方案:
第 1 秒:装满一杯冷水和一杯热水。
第 2 秒:装满一杯冷水和一杯温水。
第 3 秒:装满一杯冷水和一杯温水。
第 4 秒:装满一杯温水和一杯热水。
第 5 秒:装满一杯冷水和一杯热水。
第 6 秒:装满一杯冷水和一杯温水。
第 7 秒:装满一杯热水。
           

示例 3:

输入:amount = [5,0,0]
输出:5
解释:每秒装满一杯冷水。
           

贪心

每一次的选择分为两种情况:

  • 当未填满水杯的类型大于1时,每次都选择剩余杯子数目最多的两种进行填充
  • 当只剩下一种类型的水,单独进行填充

复杂度分析:

  • 时间复杂度: O ( c ) O(c) O(c), c c c 为三杯中数量最多的一杯。
  • 空间复杂度: O ( 1 ) O(1) O(1)
class Solution:
    def fillCups(self, amount: List[int]) -> int:
        res = 0
        while 0 not in amount:
            if amount[0] <= amount[1] and amount[0] <= amount[2]:
                amount[1] -= 1
                amount[2] -= 1
            elif amount[1] <= amount[0] and amount[1] <= amount[2]:
                amount[0] -= 1
                amount[2] -= 1
            else:
                amount[0] -= 1
                amount[1] -= 1
            res += 1
        res += max(amount)
        return res
           

来源:力扣(LeetCode)

链接:https://leetcode.cn/problems/minimum-amount-of-time-to-fill-cups