11. Container With Most Water
Asked at 47Bloomberg76Amazon76Microsoft71Google68Meta65Apple46Flipkart85tcs82Accenture71Infosys68Goldman Sachs66IBM63Cisco37PubMatic100Workday92Wix91SAP87PornHub87FreshWorks81Zoho81ServiceNow79Walmart Labs79Intel76Nvidia71Okta71Dream1168Publicis Sapient68Deloitte65Accolite64Oracle64Myntra64HashedIn62Tesla62Qualcomm58Capital One56TikTok56Yandex55Expedia54Morgan Stanley54Samsung53Capgemini52Visa48Juspay47Adobe44PayPal42Salesforce41Uber22
Problem
height[i] is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that area: (distance between them) × (the shorter height).
Example: [1,8,6,2,5,4,8,3,7] → 49 (lines at x = 1 and x = 8: 7 × 7)
Constraints: n ≤ 10⁵.
Area = min(h[l], h[r]) * (r - l). Moving the taller side can never help (width shrinks, height capped by the shorter one), so always move the shorter side.
h: 1 8 6 2 5 4 8 3 7
l r min(8,7)*7 = 49 (best)
Complexity: O(n) time, O(1) space.
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r, best = 0, len(height) - 1, 0
while l < r:
best = max(best, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return best
assert Solution().maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
assert Solution().maxArea([1, 1]) == 1
class Solution {
public int maxArea(int[] height) {
int l = 0, r = height.length - 1, best = 0;
while (l < r) {
best = Math.max(best, Math.min(height[l], height[r]) * (r - l));
if (height[l] < height[r]) l++; else r--;
}
return best;
}
}
func maxArea(height []int) int {
best := 0
for l, r := 0, len(height)-1; l < r; {
best = max(best, min(height[l], height[r])*(r-l))
if height[l] < height[r] { // the shorter wall can only get better by moving
l++
} else {
r--
}
}
return best
}