-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay24
44 lines (29 loc) · 1.32 KB
/
Day24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public double champagneTower(int k, int r, int c) {
// If no champagne is poured, the glass is empty.
if(k==0)
return 0.0;
// Create a 2D array to represent the glasses pyramid.
double [][]matrix=new double[r+1][c+2];
// Put all the poured champagne in the top glass.
matrix[0][0]=k;
for(int i=0;i<r;i++){
for(int j=0;j<=c;j++){
if(matrix[i][j]>1.0){
// Calculate excess champagne and distribute it equally to the glasses below.
double spare=matrix[i][j]-1;
// Set the current glass to hold exactly one cup.
matrix[i][j]=1;
// Distribute excess to the left glass below.
matrix[i+1][j]+=spare/2;
// Distribute excess to the right glass below.
matrix[i+1][j+1]+=spare/2;
}
}
}
// Check the value in the desired glass (r, c).
double res=matrix[r][c];
// Ensure that the value doesn't exceed 1, as each glass can hold a maximum of one cup.
return Math.min(res,1.0);
}
}