Champagne Tower LeetCode solution in C++

1
class Solution {
2
public:
3
double champagneTower(int poured, int query_row, int query_glass) {
4
vector<double> currRow(1, poured);
5

6
for (int i = 0; i <= query_row; i++) { // we need to make the dp matrix only till query row. No
7
// need to do after that
8
vector<double> nextRow(i + 2, 0); // If we are at row 0, row 1 will have 2 glasses. So next
9
// row will have currRow number + 2 number of glasses.
10
for (int j = 0; j <= i; j++) { // each row will have currRow number + 1 number of glasses.
11
if (currRow[j] >= 1) { // if the champagne from the current glass is being overflowed.
12
nextRow[j] +=
13
(currRow[j] - 1) / 2.0; // fill the left glass with the overflowing champagne
14
nextRow[j + 1] +=
15
(currRow[j] - 1) / 2.0; // fill the right glass with the overflowing champagne
16
currRow[j] = 1; // current glass will store only 1 cup of champagne
17
}
18
}
19
if (i != query_row)
20
currRow = nextRow; // change the currRow for the next iteration. But if
21
// we have already reached the query_row, then the
22
// next iteration will not even take place, so the
23
// currRow is the query_row itself. So don't change
24
// as we need the currRow only.
25
}
26
return currRow[query_glass];
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0