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

现有一台饮水机,可以制备冷水、温水和热水。每秒钟,可以装满 2 杯 不同 类型的水或者 1 杯任意类型的水。
给你一个下标从 0 开始、长度为 3 的整数数组 amount ,其中 amount[0]、amount[1] 和 amount[2] 分别表示需要装满冷水、温水和热水的杯子数量。返回装满所有杯子所需的 最少 秒数。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-amount-of-time-to-fill-cups
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

评论区都是数学解,我就想用程序解,然后被一道简单题干服了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution(object):
def fillCups(self, amount):
"""
:type amount: List[int]
:rtype: int
"""
sequence = deque()
mapping = {0:"Cold",1:"Normal",2:"Hot"}
#每次将amount中的最大值和最小值对应的饮品加入队列
while amount[0] or amount[1] or amount[2]:
index_max = amount.index(max(amount))
sequence.appendleft(mapping[index_max])
amount[index_max] -= 1
#杯数相同时直接使用index会报错,所以需要带着索引排序,就可以直接使用最小值的索引
temp = [(amount[i],i) for i in range(len(amount)) if amount[i] > 0 and i != index_max]
temp.sort()
if temp:
index_min = temp[-1][-1]
if index_max != index_min:
sequence.appendleft(mapping[index_min])
amount[index_min] -= 1
cost = 0
#每次从队列中pop两个值出来,不同cost + 1,相同cost + 2,有空值或均为空时退出循环
while True:
try:
type1 = sequence.pop()
except:
type1 = None
try:
type2 = sequence.pop()
except:
type2 = None
if type1 and type2:
if type1 != type2:
cost += 1
else:
cost += 2
elif type1 or type2:
cost += 1
break
else:
break
return cost