Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
题目大意是给一个高度数组,求其中两块隔板之间围出来的面积最大值,而且注意这个形状的高度是两块隔板间最低的高度。
单纯的n^2算法会超时,但是可以注意到一个有意思的性质,如果移动R,如果R>L,就算R变得更加高,但是因为L没有变化那么面积也不会变大,同样移动L也是。也就是说,一次只需要移动一个隔板,只到两个隔板相遇,答案就是之前所得面积中的最大值。
C# Code
public class Solution
{
public int MaxArea(int[] height)
{
if (height.Length < 2) return 0;
int ans = 0, l = 0, r = height.Length - 1;
while (l < r)
{
int v = (r - l) * (height[l] < height[r] ? height[l] : height[r]);
ans = v > ans ? v : ans;
if (height[l] < height[r]) l++; else r--;
}
return ans;
}
}
另外安利一首好歌
我现在满脑子GILIGILI EYE~GILIGILI MIND~
いけないボーダーライン