Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

Analyse: Set two variables, left and right to represent the leftmost and rightmost element respectively. We increase left and decrease right gradually. If the moving items are smaller than height[left] and height[right], then we don't need to change the value of left and right. Otherwise, we change the values and compare the area with the former computed one. 

Runtime: 32ms.

 1 class Solution {
 2 public:
 3     int maxArea(vector<int>& height) {
 4         if(height.empty()) return 0;
 5         
 6         int left = 0, right = height.size() - 1;
 7         int result = 0;
 8         while(left <= right){
 9             int h = min(height[left], height[right]);
10             result = max(result, h * (right - left));
11             
12             if(height[left] > height[right]){
13                 int index = right;
14                 while(left <= index && height[index] <= height[right])
15                     index--;
16                 right = index;
17             }
18             else{
19                 int index = left;
20                 while(index <= right && height[index] <= height[left])
21                     index++;
22                 left = index;
23             }
24         }
25         return result;
26     }
27 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4777511.html