BackmediumMath

Liquid Accumulation Solution

Problem Statement

Given a sequence of vertical bars of different heights, calculate the total amount of liquid that can accumulate between them. The liquid can accumulate between two bars if the height of the liquid does not exceed the minimum height of the two bars.

Example 1
Input
[3, 1, 2, 5, 2, 1, 6]
Output
10

Explanation: The liquid accumulates as follows: between the bars of heights 3 and 1, 1 unit can accumulate (because the minimum height of the two bars is 1); between bars 1 and 2, 1 unit; between bars 2 and 5, 2 units; between bars 5 and 2, 2 units; between bars 2 and 1, 1 unit; and between bars 1 and 6, 1 unit. Therefore, the total accumulation is 1 + 1 + 2 + 0 + 1 + 1 = 6 units.

Example 2
Input
[2, 5, 3, 7, 1, 4, 8]
Output
11

Explanation: Liquid accumulation occurs as follows: between the bars of heights 2 and 5, 2 units; between bars 5 and 3, 2 units; between bars 3 and 7, 3 units; between bars 7 and 1, 1 unit; and between bars 1 and 4, 0 units. However, the total accumulation is 2 + 2 + 3 + 0 + 1 = 8 units, because we count only the units trapped, not the units falling off the edge or blocked by higher bars.

Example 3
Input
[1, 1, 1, 1, 1, 1]
Output
0

Explanation: Since all bars are of the same height, no liquid accumulates between them.

Constraints

  • 1 <= number of bars <= 10^5
  • 1 <= height of each bar <= 10^4
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free