889. Pouring Glasses

Medium3.5 points estimatedDynamic ProgrammingSimulation3 hints

At a banquet, glasses are stacked in a pyramid: row 0 has one glass, row 1 has two, and row r has r+1 glasses, each holding exactly one cup. The server pours poured cups into the top glass. Once a glass holds more than one cup, the extra liquid is split equally and falls into the two glasses directly beneath it (down-left and down-right). Liquid falling off the sides of the bottom row is lost.

Return how full the glass at row row, position glass (both 0-indexed) is, between 0 and 1. An answer within 1e-6 is accepted.

Example 1

Input:
poured = 5, row = 2, glass = 1
Output:
1
Explanation:

The top glass overflows 4 cups, so each row-1 glass receives 2, keeps 1 and sends 0.5 to each child; the middle glass of row 2 gets 0.5 + 0.5 = 1 cup and is exactly full.

Example 2

Input:
poured = 4, row = 2, glass = 0
Output:
0.25
Explanation:

The top glass overflows 3 cups, each row-1 glass receives 1.5 and overflows 0.5, so the end glass of row 2 receives 0.25.

Example 3

Input:
poured = 1, row = 3, glass = 2
Output:
0
Explanation:

One cup fills only the top glass; nothing ever reaches row 3, so the answer is 0.

Constraints

  • 0 ≤ poured ≤ 109
  • 0 ≤ glass ≤ row ≤ 99

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(row^2)
Space
O(row^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…