LeetCode: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.

// Source : https://oj.leetcode.com/problems/container-with-most-water/  
// Author : Chao Zeng    
// Date   : 2014-12-26  
class Solution {
public:
    int maxArea(vector<int> &height) {
		int n = height.size();
		int left = 0, right = n - 1;
		int area = 0;
		while (left < right){
			int temp;
			if (height[left] < height[right])
				temp = height[left] * (right - left);
			else
				temp = height[right] * (right - left);

			if (area < temp)
				area = temp;

			if (height[left] < height[right])
				left++;
			else
				right--;
		}
		return area;
    }
};


你可能感兴趣的:(LeetCode)