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.

  解这道题,首先要读懂题目。题目要求找到一组i,j,使得area = min(ai, aj) *(j - i)最大。这题我没解出来,直接贴出答案。

solution:

int maxArea(vector<int> &height) {
    int low = 0;
    int high = height.size() - 1;
    int area = 0;
    while (low < high)
    {
        area = max(area, min(height[low], height[high]) * (high - low));
        height[low] < height[high] ? ++low : --high;
    }
    return area;
}

原文链接:https://oj.leetcode.com/discuss/1074/anyone-who-has-a-o-n-algorithm

  真有这么难想到吗?最近有点颓废,得振作起来,接着A题。

转载于:https://www.cnblogs.com/gattaca/p/4274155.html

上一篇:LeetCode.11-装水最多的容器(Container With Most Water)


下一篇:刷题11. Container With Most Water