Algorithm/NeetCode

Champagne Tower

Tony Lim 2024. 11. 18. 10:04
728x90

https://leetcode.com/problems/champagne-tower/description/

class Solution:
    def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
        prev_row = [poured] # Flow

        for row in range(1, query_row + 1):
            cur_row = [0] * (row + 1)
            for i in range(row):
                extra = prev_row[i] - 1
                if extra > 0:
                    cur_row[i] += 0.5 * extra
                    cur_row[i+1] += 0.5 * extra
            prev_row = cur_row

        return min(1,prev_row[query_glass])

flow meaning how many are actually going though that glass

the 1st iteration is about how many row we are going to look and in each iteration we are going to look for 2 array , previous and current row.

we init prev_row and start with 1st row.

2nd iteration is about prev row, how many flow does prev row have , and each iteration calculat overflow and pour to current row evenly

and update prev_row to cur_row until we meet target.

at return it is either 1 or less than 1 , because flow can be overflowed.

728x90

'Algorithm > NeetCode' 카테고리의 다른 글

Sum of Absolute Differences in a Sorted Array  (0) 2024.11.20
Majority Element II  (0) 2024.11.19
Minimum Penalty for a Shop  (0) 2024.11.17
Design Underground System  (0) 2024.11.15
Optimal Partition of String  (0) 2024.11.14