1. 程式人生 > >演算法設計與分析(8)-- Container With Most Water(難度:Medium)

演算法設計與分析(8)-- Container With Most Water(難度:Medium)

演算法設計與分析(8)

題目: 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 and n is at least 2.

演算法思路:

這個問題的本質是,有n個點(k,ak),1≤k≤n。我們找出其中兩個點,(i,ai),(j,aj),1≤i≤j≤n,使得 (j - i)*Min(ai, aj) 最大。這裡可能很容易會想到使用動態規劃的辦法,但這種方法複雜度高,我們這裡直接給出一個O(n)的簡單求解演算法。
1.n個點是存放在陣列vector<int> height中。首先,初始化 i,j 分別指向陣列的頭和尾。使用max記錄最大值。

int i = 0, j = height.size
() - 1; int max = 0;

2.然後使用while(i < j)迴圈,並用 ht = Min(height[i], height[j])。
(1)然後如果 (j - i) * ht > max成立, 那麼更新max:

(2)如果 height[i] <= ht 或者 height[j] <= ht 成立,那麼為了能夠找到更大的max值,我們分別使用 i++和 j–。當條件(i ≥ j)成立時,我們已經遍歷完成,同時找出了max的最大值。

while (i < j)
{
    int ht = Min(height[i], height[j]);
    if
((j - i) * ht > max) max = (j - i) * ht; while (height[j] <= ht && i < j) --j; while (height[i] <= ht && i < j) ++i; }

實現程式碼:

int Min(int n, int m)
{
    return n <= m ? n : m;
}

int maxArea(vector<int>& height) {
    int i = 0, j = height.size() - 1;
    int max = 0;
    while (i < j)
    {
        int ht = Min(height[i], height[j]);
        if ((j - i) * ht > max)
            max = (j - i) * ht;
        while (height[j] <= ht && i < j) --j;
        while (height[i] <= ht && i < j) ++i;
    }
    return max;
}

int main()
{

    int a[7] = { 7,6,5,4,3,2,1 };
    vector<int> height(a, a + 7);
    int result = maxArea(height);
    cout << result << endl;
    return 0;
}