周赛题

Leetcode Link: 装满杯子需要的最短总时长 - 力扣 (LeetCode) 竞赛

题目

现有一台饮水机,可以制备冷水、温水和热水。每秒钟,可以装满 2 杯 不同 类型的水或者 1 杯任意类型的水。

给你一个下标从 0 开始、长度为 3 的整数数组 amount ,其中 amount[0]amount[1] 和 amount[2] 分别表示需要装满冷水、温水和热水的杯子数量。返回装满所有杯子所需的 最少 秒数。

解法一

思路:仔细观察给出的例子,考虑怎么模拟才是正确的。

正确模拟需要在模拟的时候考虑下面的几个条件

  1. 每次接水必需接剩下的杯子中最多的那个
  2. 另一个被接的水杯必须是剩下的两个中最多的那个。
  3. 其余两个都为0时,只接不为0的

只有这样才能保证最多的那个杯子被充分的利用,不能简单的把最快开始第一第二多的杯子直接全部接完。

题解

class Solution:
    def fillCups(self, amount: List[int]) -> int:
        res = 0
        while(sum(amount)!=0):
            # 找第一个必需接的杯子(最多的那个)
            must = 0
            for i in range(len(amount)):
                if amount[i]>amount[must]:
                    must = i
            # 找第二个必需接的杯子(次多的那个)
            another = 0 if must!=0 else 1
            for i in range(len(amount)):
                if i == must:
                    continue
                else:
                    if amount[i]>amount[another]:
                        another = i
            
            # 确定第二必需接的杯子个数不是0
            if amount[another] == 0:
                amount[must] -= 1
            else:
                ## process
                amount[must] -= 1
                amount[another] -= 1
            
            res += 1
        return res

解法二

思路

题解

解法三

思路

题解

启发和联系