|
| 1 | +/** |
| 2 | + * 799. Champagne Tower |
| 3 | + * https://leetcode.com/problems/champagne-tower/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and |
| 7 | + * so on until the 100th row. Each glass holds one cup of champagne. |
| 8 | + * |
| 9 | + * Then, some champagne is poured into the first glass at the top. When the topmost glass is full, |
| 10 | + * any excess liquid poured will fall equally to the glass immediately to the left and right of it. |
| 11 | + * When those glasses become full, any excess champagne will fall equally to the left and right of |
| 12 | + * those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the |
| 13 | + * floor.) |
| 14 | + * |
| 15 | + * For example, after one cup of champagne is poured, the top most glass is full. After two cups |
| 16 | + * of champagne are poured, the two glasses on the second row are half full. After three cups of |
| 17 | + * champagne are poured, those two cups become full - there are 3 full glasses total now. After |
| 18 | + * four cups of champagne are poured, the third row has the middle glass half full, and the two |
| 19 | + * outside glasses are a quarter full, as pictured below. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} poured |
| 24 | + * @param {number} queryRow |
| 25 | + * @param {number} queryGlass |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var champagneTower = function(poured, queryRow, queryGlass) { |
| 29 | + const tower = new Array(101).fill().map(() => new Array(101).fill(0)); |
| 30 | + tower[0][0] = poured; |
| 31 | + |
| 32 | + for (let row = 0; row <= queryRow; row++) { |
| 33 | + for (let glass = 0; glass <= row; glass++) { |
| 34 | + const excess = (tower[row][glass] - 1) / 2; |
| 35 | + |
| 36 | + if (excess > 0) { |
| 37 | + tower[row + 1][glass] += excess; |
| 38 | + tower[row + 1][glass + 1] += excess; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return Math.min(1, tower[queryRow][queryGlass]); |
| 44 | +}; |
0 commit comments