LeetCode(11) Container With Most Water

2756 ワード

タイトル
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.
ぶんせき
題意は1つの高さの配列があって、仕切り板の高さに相当して、配列の中で任意の2つの仕切り板の間で水を盛る最も大量を求めます.仕切り板間の距離と低い間隔
板の高さの積は水を盛る容量である.
ACコード
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
    int maxArea(vector<int>& height) {
        if (height.empty())
            return 0;

        int maxCapacity = 0;
        size_t lhs = 0, rhs = height.size() - 1;

        while (lhs < rhs)
        { 
            int capacity = (rhs - lhs) * min(height[lhs], height[rhs]);
            if (capacity > maxCapacity)
            {
                maxCapacity = capacity;
            }

            if (height[lhs] < height[rhs])
                ++lhs;
            else
                --rhs;
        }//while
        return maxCapacity;
    }
};

int main()
{
    Solution s;
    vector<int> v = { 1, 2, 3, 4 };
    cout << s.maxArea(v) << endl;

    system("pause");
    return 0;
}

GitHubテストプログラムソースコード