1. 程式人生 > >[C++]LeetCode 11: Container With Most Water(最大容積/最大矩形面積)

[C++]LeetCode 11: Container With Most Water(最大容積/最大矩形面積)

Problem:

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.

分析:

題目即為求(i, ai),(i, 0),(j, aj),(j, 0)組成的圖形的最大矩形面積面積(以ai和aj中小者為矩形的高)。

利用二分法,衝首位兩邊縮排,每次求得面積與最大面積比較並更新,

同時對ai,aj中小者的位置進行更新(大者可能會成為下一次的高以更新面積;而小者不變只能得到小於等於小者的高,且寬度在減小無法更新面積)。

AC Code(C++):

class Solution {
public:
    //45 / 45 test cases passed.
    //Runtime: 29 ms
    
    int maxArea(vector<int>& height) {
        //排除無效情況
        if (height.size() < 2) {
            return 0;
        }
        
        int begin = 0;
        int end = (int)height.size() - 1;
        int container = 0;
        while (begin < end) {
            int size = min(height[begin], height[end])*(end - begin);
            if (size > container) {
                container = size;
            }
            if (height[begin] < height[end]) {
                ++begin;
            }
            else{
                --end;
            }
        }
        return container;
    }
};