2017-09-09 LeetCode_011 Container With Most Water

11. 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 and n is at least 2.

solution:
class Solution {
2
public:
3
    int maxArea(vector<int>& height) {
4
        int n = height.size(), ans = -1;
5
        int i = 0, j = n-1;
6
        while (i < j) {
7
            if (height[i] < height[j]) {
8
                ans = ans > height[i]*(j-i) ? ans : height[i]*(j-i);
9
                i++;
10
            } else {
11
                ans = ans > height[j]*(j-i) ? ans : height[j]*(j-i);
12
                j--;
13
            }
14
        }
15
        return ans;
16
    }
17
};










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章