Minimum Amount of Time to Fill Cups - Problem

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
  • Fill up 1 cup of any type of water

You are given a 0-indexed integer array amount of length 3 where:

  • amount[0] = number of cold water cups needed
  • amount[1] = number of warm water cups needed
  • amount[2] = number of hot water cups needed

Return the minimum number of seconds needed to fill up all the cups.

Input & Output

Example 1 — Balanced Distribution
$ Input: amount = [1,4,2]
Output: 4
💡 Note: Optimal strategy: Fill warm+hot (1 sec) → [1,3,1], Fill warm+hot (1 sec) → [1,2,0], Fill cold+warm (1 sec) → [0,1,0], Fill warm (1 sec) → [0,0,0]. Total: 4 seconds.
Example 2 — One Dominant Type
$ Input: amount = [5,4,4]
Output: 7
💡 Note: With 5 cold cups, we can pair optimally until other types run out. Cold+warm and cold+hot simultaneously for 4 seconds, then 1 cold cup remains, taking 1 more second. Total: 5 + 2 = 7 seconds.
Example 3 — Equal Amounts
$ Input: amount = [5,0,0]
Output: 5
💡 Note: Only one type available, so we must fill one cup per second for 5 seconds. No pairing possible.

Constraints

  • amount.length == 3
  • 0 ≤ amount[i] ≤ 100

Visualization

Tap to expand
Minimum Amount of Time to Fill Cups INPUT WATER DISPENSER Cold Warm Hot amount = [1, 4, 2] 1 Cold 4 Warm 2 Hot Rules per second: Fill 2 cups (different types) OR Fill 1 cup (any type) Total cups: 1+4+2 = 7 ALGORITHM STEPS Max Heap Priority Queue 1 Build max heap Heap: [4, 2, 1] 2 Pop 2 largest Pop 4,2 then decrement 3 Push back if > 0 Reinsert non-zero values 4 Repeat until empty Count seconds Simulation: Sec 0: [4,2,1] Sec 1: Pop 4,2 --> [3,1,1] Sec 2: Pop 3,1 --> [2,1,0] Sec 3: Pop 2,1 --> [1,0,0] Sec 4: Pop 1 --> [0,0,0] Heap empty! Done. Total: 4 seconds FINAL RESULT Timeline of Operations Second 1: Warm+Hot Second 2: Warm+Cold Second 3: Warm+Hot Second 4: Warm only Output: 4 OK - All cups filled! Key Insight: Greedy approach: Always fill the two types with the most cups remaining to maximize efficiency. Using a max heap ensures O(log n) extraction of the two largest values each second. Formula hint: Answer = max(max(amount), ceil(sum(amount)/2)) since we fill at most 2 cups/sec. TutorialsPoint - Minimum Amount of Time to Fill Cups | Greedy with Priority Queue
Asked in
Google 15 Microsoft 8 Amazon 12
32.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen