To be honest, I don’t really know how to explain the solution clearly. It’s kind of a “greedy” solution: for each tank, you try to use this to reduce the water in previous tanks. Specifically, you can see water tanks as a succession of groups, if the current group has a smaller average value than the left one, then merge them. The stack is used to store the number of tanks and the sum of water.