LeetCode Online Judge 题目C# 练习 - Container With Most Water
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.
public static int MaxArea(int[] height) { int a = 0; //建立a指针指向最左端 int b = height.GetUpperBound(0); //建立b指针指向最右端 int max_area = 0; while (a < b) //当a还在b的左边 { int curr_area = Math.Min(height[a], height[b]) * (b - a); //计算当前 a , b 与x轴围起来的面积 max_area = curr_area > max_area ? curr_area : max_area; //如果当前面积比max_area打,替换之 if (height[a] > height[b]) //如果 height[a] > height[b],b往左移 { while (height[--b] < height[b]); //直到找到b的上升沿,因为,如果是下降沿,面积一定没之前大 } else //如果 height[a] <= height[b],a往左移 { while (height[++a] < height[a]) ; //直到找到a的上升沿,因为,如果是下降沿,面积一定没之前大 } } return max_area; }
代码分析:
建两个指针分别从两端往中间靠拢, 算出面积,如果比之前最大的面积大,就替换max_area变量。