Champagne Tower — LeetCode 799 Python Solution
- Problem
- #799
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Example
- Input
- poured = 1, query_row = 1, query_glass = 1
- Output
- 0.00000
- Explanation
- We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
Python solution
class Solution:
def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
f = [[0] * 101 for _ in range(101)]
f[0][0] = poured
for i in range(query_row + 1):
for j in range(i + 1):
if f[i][j] > 1:
half = (f[i][j] - 1) / 2
f[i][j] = 1
f[i + 1][j] += half
f[i + 1][j + 1] += half
return f[query_row][query_glass]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 799. Champagne Tower is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 799. Champagne Tower?
- LeetCode 799. Champagne Tower is rated Medium on LeetCode.
- What topics does LeetCode 799. Champagne Tower cover?
- LeetCode 799. Champagne Tower is tagged Dynamic Programming on LeetCode.