Why does the given approach always work for this question?

The logic I applied is as follows:
We need the maximum area.
Area
= width * height
= (end - start) * Min(start, end)
The width is always decreasing when we change either start or end.
To get maximum area height is the contributing factor.
So, to get the maximum height, we need to change the smaller wall.

Can anyone confirm if this makes sense?
If it does, how do we always get the expected maximum area using this logic?

Yes @seeker001 . The logic you are using is perfect. You can also use Debrief section to verify. Inorder to get the max area, either we have to increase the width or we have to increase the height. We already start with maximum width so we can’t increase width anymore. But inorder to increase the area we keep on changing the lower side (either of start or end) till both crosses each other.

Now, let’s understand why this will always work. Assume Height at index 0 is 5 and index 7 is 15. Right now, how much water we can hold by considering just this 2 heights? We can hold (end-start)*min(height[start], height[end]) = (7-0) * min(5,15) = 70. Now think will it help to get any other heights even more than 15 by keeping the same height of another line that is 5 here? The answer is No it won’t help as it does not matter as we can only save up to min(height[start], height[end]) height and extra water will fall away. Now think will it help to find any other line with height more than 5 and keep 15’s line the same? The answer is it might be helpful if its height is more than 5 then we may save more water as min(height[start], height[end]) will be more now.

I hope the explanation is clear now. If not try it with some examples on the paper to understand better. Feel free to post again if it is still unclear or needs more explanation.

1 Like

Thank you @Aditya_Crio.Do_TA!

is your query resolved, if yes mark the reply as solution.

Closing this topic as your issue has been resolved by the community. If not Kindly un-mark the accepted solution to re-open the topic or feel free to create a new topic and post a link to this topic as a reference.

Re-opening this topic as the previously accepted solution was just Un-marked.

Re-opening this topic as the previously accepted solution was just Un-marked.

Closing this topic as your issue has been resolved by the community. If not Kindly un-mark the accepted solution to re-open the topic or feel free to create a new topic and post a link to this topic as a reference.