#799
Champagne Tower
MediumDynamic ProgrammingDynamic Programming2D Arrays
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of simulating the entire pouring process, we can use a dynamic programming approach to calculate the amount of champagne in each glass directly. This avoids unnecessary computations and reduces time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array to hold the amount of champagne in each glass.
- 2Step 2: Pour champagne into the top glass and iterate through each row.
- 3Step 3: For each glass, if it overflows, distribute the excess to the glasses below.
solution.py13 lines
1# Full working Python code
2class Solution:
3 def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
4 glasses = [[0] * (i + 1) for i in range(101)]
5 glasses[0][0] = poured
6 for i in range(100):
7 for j in range(i + 1):
8 if glasses[i][j] > 1:
9 excess = glasses[i][j] - 1
10 glasses[i][j] = 1
11 glasses[i + 1][j] += excess / 2
12 glasses[i + 1][j + 1] += excess / 2
13 return min(1, glasses[query_row][query_glass])ℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the rows until we reach the query row. The space complexity is O(n) due to the storage of the glasses array.
- 1Champagne flows downwards and splits equally between two glasses below.
- 2Each glass can hold a maximum of 1 cup; any excess is distributed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.