#2335

Minimum Amount of Time to Fill Cups

Easy
ArrayGreedySortingHeap (Priority Queue)Greedy AlgorithmsPriority Queue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a greedy approach to always fill the two cups with the most water left. This minimizes the total time by maximizing the number of cups filled each second.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the amount array in descending order.
  2. 2Step 2: While the largest amount is greater than 0, fill the two largest cups.
  3. 3Step 3: If only one cup remains, fill it until it's empty.
solution.py16 lines
1# Full working Python code
2import heapq
3amount = [1, 4, 2]
4seconds = 0
5amount = [-x for x in amount]  # Use max-heap
6heapq.heapify(amount)
7while amount:
8    first = -heapq.heappop(amount)
9    if amount:
10        second = -heapq.heappop(amount)
11        if second > 1:
12            heapq.heappush(amount, -(second - 1))
13    seconds += 1
14    if first > 1:
15        heapq.heappush(amount, -(first - 1))
16return seconds

Complexity note: The complexity is O(n log n) due to the heap operations for maintaining the max-heap, which allows us to efficiently get the two largest amounts.

  • 1Maximizing the number of cups filled each second reduces total time.
  • 2Using a greedy approach with a priority queue allows efficient selection of the largest amounts.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.