Tags: two pointer


Problem Statement:
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

question_11.jpg

Intuition:
To get the max water container, i.e., maximise the area btw two pair.
So, since area = length x breadth, the breadth here is distance between two pillars, to maximise that l and r should be apart as possible, then based on the height of the pillar at l and r move the pointer.

Code:

def solve(height):
	n = len(height)
	l, r = 0, n-1
	res = 0
	while l < r:
		area = (r-l) * min(height[l], height[r])
		res = max(res, area)
		if height[l] < height[r]:
			l += 1
		else:
			r -= 1
	return res 

Leetcode Link