You are given a 0-indexed integer array amount
of length 3
where amount[0]
, amount[1]
, and amount[2]
represent the number of cold, warm, and hot water cups you need to fill respectively. You can only fill two cups at a time, and it takes 1 second to fill either one or two cups. Return the minimum number of seconds needed to fill all the cups.
Example 1:
Input: amount = [1,4,2]
Output: 4
Explanation: One way to fill the cups is:
Second 1: Fill the 1st and 3rd cup.
Second 2: Fill the 3rd cup.
Second 3: Fill the 2nd cup.
Second 4: Fill the 2nd cup.
Example 2:
Input: amount = [5,4,4]
Output: 7
Explanation: One way to fill the cups is:
Second 1: Fill the 1st and 2nd cup.
Second 2: Fill the 1st and 3rd cup.
Second 3: Fill the 1st and 2nd cup.
Second 4: Fill the 1st and 2nd cup.
Second 5: Fill the 1st and 3rd cup.
Second 6: Fill the 2nd and 3rd cup.
Second 7: Fill the 1st cup.
Example 3:
Input: amount = [5,0,0]
Output: 5
Explanation: Every second, we can only fill the 1st cup.
amount
contain negative numbers?
amount
?
def fillCups(amount):
amount.sort()
# The number of seconds required will be the largest of
# the maximum value in `amount` or half the sum (rounded up).
return max(amount[2], (sum(amount) + 1) // 2)
# Test cases
print(fillCups([1, 4, 2])) # Output: 4
print(fillCups([5, 4, 4])) # Output: 7
print(fillCups([5, 0, 0])) # Output: 5
The space complexity is also (O(1)) because we are only using a fixed amount of extra space for variables regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?