You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.
You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.
Example 1:
Input: amount = [1,4,2] Output: 4 Explanation: One way to fill up the cups is: Second 1: Fill up a cold cup and a warm cup. Second 2: Fill up a warm cup and a hot cup. Second 3: Fill up a warm cup and a hot cup. Second 4: Fill up a warm cup. It can be proven that 4 is the minimum number of seconds needed.
Example 2:
Input: amount = [5,4,4] Output: 7 Explanation: One way to fill up the cups is: Second 1: Fill up a cold cup, and a hot cup. Second 2: Fill up a cold cup, and a warm cup. Second 3: Fill up a cold cup, and a warm cup. Second 4: Fill up a warm cup, and a hot cup. Second 5: Fill up a cold cup, and a hot cup. Second 6: Fill up a cold cup, and a warm cup. Second 7: Fill up a hot cup.
Example 3:
Input: amount = [5,0,0] Output: 5 Explanation: Every second, we fill up a cold cup.
Constraints:
amount.length == 30 <= amount[i] <= 100
Related Topics:
Array, Greedy, Sorting, Heap (Priority Queue)
Similar Questions:
- Construct Target Array With Multiple Sums (Hard)
- Maximum Score From Removing Stones (Medium)
- Maximum Running Time of N Computers (Hard)
- Minimum Cost to Make Array Equal (Hard)
// OJ: https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int fillCups(vector<int>& A) {
int ans = 0;
priority_queue<int> pq;
for (int n : A) {
if (n) pq.push(n);
}
while (pq.size() >= 2) {
int a = pq.top();
pq.pop();
int b = pq.top();
pq.pop();
if (a - 1 > 0) pq.push(a - 1);
if (b - 1 > 0) pq.push(b - 1);
++ans;
}
if (pq.size()) ans += pq.top();
return ans;
}
};// OJ: https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
// Ref: https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/solutions/2261394/java-c-python-max-max-a-sum-a-1-2/
class Solution {
public:
int fillCups(vector<int>& A) {
int mx = 0, sum = 0;
for (int n : A) {
mx = max(mx, n);
sum += n;
}
return max(mx, (sum + 1) / 2);
}
};