1. Container With Most Water

Link to the problem

Description

Givennnon-negative integers a1,a2, ...,an, where each represents a point at coordinate (i,ai).nvertical lines are drawn such that the two endpoints of lineiis 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 andnis at least 2.

Examples

Input: [1, 1], Output: 1
The two lines are (0, 0)--(0, 1) and (1, 0)--(1,1), the rectangle they form has height 1, and width 1. So the area is 1.

Input: [2, 1, 3], Output: 4
The best lines are (0, 0)--(0, 2) and (2, 0)--(2, 3), the rectangle they form has height 2, and width 2. So the area is 4.

Idea

We want to find i < j, such that (j - i)min(ai, aj) is maximized.
Assume we are now at i = left and j = right, and by symmetry, ai < aj, then by decrementing j and fix that i, we can only make their minimum smaller, but their difference is strictly smaller, so we can never increase the area between. Hence, it only makes sense to move the lower bar, and never move the higher one. We use two pointers to maintain the i and j we are searching.

Solution

class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
        int left = 0, right = n - 1;
        int max_area_so_far = 0;
        while (left < right) {
            int curr_area = min(height[left], height[right]) * (right - left);
            max_area_so_far = max(max_area_so_far, curr_area);
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return max_area_so_far;
    }
};

Performance

49 / 49 test cases passed.
Runtime: 16 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今年过年回家,因为没攒下钱,被父母劈头盖脸的骂了一顿,虽然心里不好受,但也只能默默的接受,因为他们骂的没错,除了郁...
    幕影心阅读 3,980评论 0 3
  • 金枝玉叶任天真,国破家亡恨深深。 阴差阳错进李府,几经磨难把冤申。 同根相煎何太急,机关算尽梦一场。 不选江山选美...
    迹远留香阅读 3,567评论 5 5
  • 那一年桃花开 那一年你一袭粉红 美若仙子,三千青丝 而今的你,远在天涯 而今的我,却望常伴 而今的你,已是暮年 而...
    栩辰徉阅读 1,391评论 2 2
  • 终于在清明假期看了电影《情人》,影片结束很久了,心中却残留着屡屡遗憾。为东尼与简的擦肩而过而遗憾,也为古往今来相爱...
    晏耀飞阅读 4,035评论 3 5