Advertisement
11. Container With Most Water
MediumView on LeetCode
Time: O(n)
Space: O(1)
Approach
Two pointers from both ends. Move the pointer at the shorter height inward; the area is always limited by the shorter side.
11.cs
C#
// Approach: Two pointers from both ends. Move the pointer at the shorter height
// inward; the area is always limited by the shorter side.
// Time: O(n) Space: O(1)
public class Solution
{
public int MaxArea(int[] height)
{
int n = height.Length;
int l = 0;
int r = n - 1;
int maxWater = 0;
while (l <= r)
{
if (height[l] <= height[r])
{
int water = height[l] * (r - l);
maxWater = Math.Max(water, maxWater);
l++;
}
else
{
int water = height[r] * (r - l);
maxWater = Math.Max(water, maxWater);
r--;
}
}
return maxWater;
}
}Advertisement
Was this solution helpful?