Ctrl K

Absorbing From the Right

Medium
Drops of water sit in a row, and sizes[i] is the volume of drop i. A drop may absorb its **left** neighbour if that neighbour is not larger than itself: the neighbour disappears, the drop's volume becomes the sum of the two, and the row closes up. You may absorb as many times as you like, in any order, or not at all. What is the largest volume a single drop can end up with? Formally, you may pick an index i with sizes[i] <= sizes[i + 1], replace sizes[i + 1] with sizes[i] + sizes[i + 1] and delete sizes[i]. Return the maximum of the final array under the best sequence of operations.
Example 1
sizes=[4, 6, 1, 2, 8] → 21

Since 2 ≤ 8, the 8 absorbs its left neighbour and becomes 10. Then 1 ≤ 10 gives 11, 6 ≤ 11 gives 17, 4 ≤ 17 gives 21. A single value 21 remains.

Example 2
sizes=[9, 3, 2] → 9

3 > 2 and 9 > 3, so no absorption is possible at all. The largest value is 9.

Example 3
sizes=[7, 2, 5] → 14

5 absorbs 2 and becomes 7; then 7 ≤ 7, so the right 7 absorbs the left one, giving 14.

Constraints
  • 1 ≤ len(sizes) ≤ 10⁵
  • 1 ≤ sizes[i] ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumWhere to Start the Lap Medium
loading Python…
Input
sizes=[4, 6, 1, 2, 8]
Expected
21

Run checks the first 3 tests in your browser. Submit checks all 127 tests on the server, hidden ones included.