Minimum Amount of Time to Fill Cups solution and explanation
9 more videos on this problem
Weekly Contest 301 | Leetcode 2335 Minimum Amount of Time to Fill Cups | Easy HeapsCoding Decoded · 7:08 · 2K views
Leetcode 2335 Minimum Amount of Time to Fill Cups | HindiThinkCode · 6:11 · 2K views
6112. Minimum Amount of Time to Fill CupsLiVe-CoDiNg · 0:35 · 1K views
2335. Minimum Amount of Time to Fill Cups (Leetcode Easy)Programming Live with Larry · 3:28 · 1K views
2335. Minimum Amount of Time to Fill Cups | LEETCODE EASYcode Explainer · 7:44 · 875 views
Leetcode Weekly contest 301 - Easy - Minimum Amount of Time to Fill CupsPrakhar Agrawal · 8:57 · 698 views
Minimum Amount of Time to Fill Cups || LeetCode 2335 || Sorting || Greedy || Weekly Contest 301BottomUp · 9:47 · 585 views
【每日一题】LeetCode 2335. Minimum Amount of Time to Fill CupsHuifeng Guan · 19:00 · 406 views
2335 Minimum Amount of Time to Fill Cups Leetcode Weekly Contest 301Ashutosh sharma · 6:26 · 283 views
Minimum Amount of Time to Fill Cups - LeetCode 2335 - Java Solutionalgobest - Computer Science · 2:46 · 171 views
The 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 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
Approach overview
Problem Overview: You are given an array amount where each element represents the number of cold, warm, and hot cups to fill. Each second you can either fill two different types of cups or one cup of any type. The task is to compute the minimum number of seconds required to finish filling all cups.
Approach 1: Greedy Counting (O(1) time, O(1) space)
The key observation is that one second can process two different cup types simultaneously. The total work is the sum of all cups, but you cannot process more than one cup of the same type per second. Sort the three values or compute the maximum directly. The minimum time is max(max(amount), ceil(sum(amount)/2)). The first term handles the case where one type dominates, while the second term represents pairing cups whenever possible. This greedy reasoning avoids simulation and works in constant time because the array size is fixed. The approach relies on simple array manipulation and a classic greedy observation.
Approach 2: Priority Queue (Heap) Simulation (O(n log 3) time, O(1) space)
This method simulates the process using a max heap. Push the three cup counts into a priority queue. Each second, pop the two largest values, decrement both, and push them back if they are still positive. If only one type remains, decrement it alone. The heap ensures the two largest counts are always chosen, which maximizes parallel filling each second. Because the heap size never exceeds three elements, operations are cheap, but the loop runs for roughly the total number of seconds required.
Recommended for interviews: Interviewers usually expect the greedy observation. The heap simulation demonstrates understanding of priority queues, but the constant-time greedy formula shows stronger problem insight and leads to the most optimal solution.
Approach 1: Greedy Approach
The greedy approach involves selecting the largest possible numbers from the amount array to fill in pairs such that the number of seconds is minimized. By always aiming to fill two types of water at once, we can quickly reduce the total amount.
def fillCups(amount):
total = sum(amount)
max_val = max(amount)
return max(max_val, (total + 1) // 2)
if __name__ == "__main__":
amount = [1, 4, 2]
print(fillCups(amount))import java.util.*;
public class FillCups {
public int fillCups(int[] amount) {
int max = Arrays.stream(amount).max().orElse(0);
int total = Arrays.stream(amount).sum();
return Math.max(max, (total + 1) / 2);
}
public static void main(String[] args) {
FillCups fc = new FillCups();
int[] amount = {1, 4, 2};
System.out.println(fc.fillCups(amount));
}
}#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int fillCups(vector<int>& amount) {
int max_value = *max_element(amount.begin(), amount.end());
int total = amount[0] + amount[1] + amount[2];
return max(max_value, (total + 1) / 2);
}
int main() {
vector<int> amount = {1, 4, 2};
cout << fillCups(amount) << endl;
return 0;
}function fillCups(amount) {
const total = amount.reduce((a, b) => a + b, 0);
const maxVal = Math.max(...amount);
return Math.max(maxVal, Math.ceil(total / 2));
}
const amount = [1, 4, 2];
console.log(fillCups(amount));#include <stdio.h>
int fillCups(int* amount, int amountSize) {
int max = 0, total = 0;
for (int i = 0; i < amountSize; i++) {
if (amount[i] > max)
max = amount[i];
total += amount[i];
}
return total / 2 + total % 2 > max ? total / 2 + total % 2 : max;
}
int main() {
int amount[] = {1,4,2};
int result = fillCups(amount, 3);
printf("%d\n", result);
return 0;
}using System;
using System.Linq;
public class FillCupsProblem {
public int FillCups(int[] amount) {
int max = amount.Max();
int total = amount.Sum();
return Math.Max(max, (total + 1) / 2);
}
public static void Main() {
int[] amount = {1, 4, 2};
FillCupsProblem fcp = new FillCupsProblem();
Console.WriteLine(fcp.FillCups(amount));
}
}This Python solution computes the total and maximum of the input using built-in functions. It then determines the result by comparing the highest value with half the total rounded up.
Time Complexity: O(1) because operations on a constant-sized list.
Space Complexity: O(1) since no extra data structures are needed.
Approach 2: Priority Queue (Heap) Approach
This method uses a priority queue to always prioritize filling the largest cups first. By maintaining the heap order, we can dynamically get and reduce the largest values effectively.
import heapq
def fillCups(amount):
amount = [-a for a in amount] # Negate values for max-heap
heapq.heapify(amount)
seconds = 0
while amount[0] < 0: # Negative largest
first = heapq.heappop(amount)
second = heapq.heappop(amount)
if first < 0: first += 1
if second < 0: second += 1
heapq.heappush(amount, first)
heapq.heappush(amount, second)
seconds += 1
return seconds
if __name__ == "__main__":
amount = [1, 4, 2]
print(fillCups(amount))import java.util.*;
public class FillCups {
public int fillCups(int[] amount) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int a : amount) pq.add(a);
int seconds = 0;
while (pq.peek() > 0) {
int first = pq.poll();
int second = pq.poll();
if (first > 0) first--;
if (second > 0) second--;
pq.add(first);
pq.add(second);
seconds++;
}
return seconds;
}
public static void main(String[] args) {
FillCups fc = new FillCups();
int[] amount = {1, 4, 2};
System.out.println(fc.fillCups(amount));
}
}#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int fillCups(vector<int>& amount) {
priority_queue<int> pq(amount.begin(), amount.end());
int seconds = 0;
while (pq.top() > 0) {
int first = pq.top(); pq.pop();
int second = pq.top(); pq.pop();
if (first > 0) first--;
if (second > 0) second--;
pq.push(first);
pq.push(second);
seconds++;
}
return seconds;
}
int main() {
vector<int> amount = {1, 4, 2};
cout << fillCups(amount) << endl;
return 0;
}Max-Heap implementation in JavaScript requires additional boilerplate as JS lacks native heap structures. Using sorting or array manipulations can mimic this but is verbose and not optimal in short examples.C does not have a built-in priority queue but you can simulate one using manual sorting and/or a custom heap.
This approach is not readily demonstrated in C due to its manual memory management and absence of dynamic arrays or built-in priority queue structures.using System;
using System.Collections.Generic;
public class FillCupsProblem {
public int FillCups(int[] amount) {
PriorityQueue<int, int> pq = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
foreach (var a in amount) pq.Enqueue(a, a);
int seconds = 0;
while (pq.Peek() > 0) {
int first = pq.Dequeue();
int second = pq.Dequeue();
if (first > 0) first--;
if (second > 0) second--;
pq.Enqueue(first, first);
pq.Enqueue(second, second);
seconds++;
}
return seconds;
}
public static void Main() {
int[] amount = {1, 4, 2};
FillCupsProblem fcp = new FillCupsProblem();
Console.WriteLine(fcp.FillCups(amount));
}
}This Python solution uses a heap (priority queue) to always decrement the two largest elements. Using negated values, it simulates a max-heap with heapq.
Time Complexity: O(n log n) based on heap operations.
Space Complexity: O(1) for fixed initial array size.
Approach 3: Default Approach
function fillCups(amount: number[]): number {
amount.sort((a, b) => a - b);
let [a, b, c] = amount;
let diff = a + b - c;
if (diff <= 0) return c;
else return Math.floor((diff + 1) / 2) + c;
}func fillCups(amount []int) int {
ans := 0
for amount[0]+amount[1]+amount[2] > 0 {
sort.Ints(amount)
ans++
amount[2]--
if amount[1] > 0 {
amount[1]--
}
}
return ans
}impl Solution {
pub fn fill_cups(mut amount: Vec<i32>) -> i32 {
amount.sort();
let dif = amount[0] + amount[1] - amount[2];
if dif <= 0 {
return amount[2];
}
(dif + 1) / 2 + amount[2]
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Greedy Approach | Time Complexity: O(1) because operations on a constant-sized list. |
| Priority Queue (Heap) Approach | Time Complexity: O(n log n) based on heap operations. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Formula | O(1) | O(1) | Best solution when recognizing the pairing insight between cup types |
| Priority Queue (Heap) Simulation | O(n log 3) ≈ O(n) | O(1) | Useful for understanding the process step-by-step or when extending to more cup types |
Frequently asked questions
Is Minimum Amount of Time to Fill Cups easy or hard?
Minimum Amount of Time to Fill Cups is classified as an Easy problem on LeetCode with an acceptance rate around 60%. The challenge lies in recognizing the greedy pairing insight rather than simulating every second.
Minimum Amount of Time to Fill Cups Python/Java solution
Most implementations compute the sum of the array and the maximum value, then return max(maxValue, (sum + 1) // 2). This works in Python, Java, C++, and JavaScript with only a few lines of code and constant time complexity.
How to solve Minimum Amount of Time to Fill Cups in O(n)?
A heap-based simulation achieves roughly O(n) time. Insert the three values into a max heap, repeatedly remove the two largest counts, decrement them, and push them back until all cups are filled. Since the heap size is constant (3), each operation is O(log 3).
What is the best approach for Minimum Amount of Time to Fill Cups?
The optimal approach is a greedy formula based on the total cups and the largest cup type. The answer is max(max(amount), ceil(sum(amount) / 2)). This works because each second can process at most two cups of different types. The algorithm runs in O(1) time and O(1) space.
Is Minimum Amount of Time to Fill Cups asked at Google/Amazon/Meta?
Greedy scheduling and heap simulation problems similar to this appear frequently in interviews at companies like Amazon, Google, and Meta. The exact problem may vary, but recognizing greedy pairing or using a priority queue to balance workloads is a common interview pattern.
What data structure is used in Minimum Amount of Time to Fill Cups?
Two main concepts appear in solutions: greedy reasoning and a priority queue (max heap). The greedy solution uses simple arithmetic with arrays, while the alternative simulation uses a heap to always select the two largest remaining cup counts.
What is the time complexity of Minimum Amount of Time to Fill Cups?
The optimal greedy solution runs in O(1) time because the array always contains exactly three values. It only computes the sum and the maximum element. A simulation using a heap runs in about O(n log 3), where n is the number of seconds simulated.
