Water Container Problem (Java)

Problem: Given an array of heights, find out the max area that can be formed between any two bars.

Solution: The key to solve this problem is to start from the extreme edge. Calculate the current area between two bars and compare it with the max area seen so far. Next step is to move the one side that is comparatively shorter. Meaning if the left bar is short then increment left bar index. If the right bar is short then decrement the right bar index. Do it till left bar index < right bar index.

Code:

Complexity: O(n)
As at max, it does one pass. The case could be heights are in descending order or ascending order.

Git url: https://github.com/Niravkumar-Patel/SnippetExampleRepo/blob/master/SnippetExamplePractice/src/hackerrank/WaterContainer.java

Leave a Reply

Your email address will not be published. Required fields are marked *