[LeetCode] 962. Maximum Width Ramp 最大寬度坡



Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j].  The width of such a ramp is j - i.

Find the maximum width of a ramp in A.  If one doesn't exist, return 0.

Example 1:

Input: [6,0,8,2,1,5]
Output: 4
Explanation:
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.

Example 2:

Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation:
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.

Note:

  1. 2 <= A.length <= 50000
  2. 0 <= A[i] <= 50000

這道題說給了一個數組A,這里定義了一種叫做 Ramp 的范圍 (i, j),滿足 i < jA[i] <= A[j],而 ramp 就是 j - i,這里讓求最寬的 ramp,若沒有,則返回0。其實就是讓在數組中找一前一后的兩個數字,前面的數字小於等於后面的數字,且兩個數字需要相距最遠,讓求這個最遠的距離。二話不說,博主直接上暴力搜索了,遍歷任意兩個數字的組合,只要前面的數字小於等於后面的數字,用二者間的距離更新結果 res,結果超時了,后來加了些剪枝,還是超時。看來 OJ 根本不想放平方級的復雜度一絲生路。必須要要另謀出路了,先想一下,什么時侯不存在這個 ramp,就是當數組是嚴格遞減的時候,那么不存在前面的數字小於等於后面的數字的情況,於是 ramp 是0,對於這種情況下平方級的復雜度基本都是白計算,難怪 OJ 不給過。其實這道題的優化解法應該是使用單調棧,可以參見博主之前的一篇總結帖 LeetCode Monotonous Stack Summary 單調棧小結。這里用一個數組 idx,來記錄一個單調遞減數組中數字的下標,遍歷原數組A,對於每個遍歷到的數字 A[i],判斷若此時下標數組為空,或者當前數字 A[i] 小於該下標數組中最后一個坐標在A中表示的數字時,將當前坐標i加入 idx,繼續保持單調遞減的順序。反之,若 A[i] 比較大,則可以用二分搜索法來找出單調遞減數組中第一個小於 A[i] 的數字的坐標,這樣就可以快速得到 ramp 的大小,並用來更新結果 res 即可,這樣整體的復雜度就降到了 O(nlgn),從而完美通過 OJ,參見代碼如下:


class Solution {
public:
    int maxWidthRamp(vector<int>& A) {
        int n = A.size(), res = 0;
        vector<int> idx;
        for (int i = 0; i < n; ++i) {
            if (idx.size() == 0 || A[i] < A[idx.back()]) {
                idx.push_back(i);
            } else {
                int left = 0, right = (int)idx.size() - 1;
                while (left < right) {
                    int mid = left + (right - left) / 2;
                    if (A[idx[mid]] > A[i]) {
                        left = mid + 1;
                    } else {
                        right = mid;
                    }
                }
                res = max(res, i - idx[right]);
            }
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/962


參考資料:

https://leetcode.com/problems/maximum-width-ramp/

https://leetcode.com/problems/maximum-width-ramp/discuss/208348/JavaC%2B%2BPython-O(N)-Using-Stack

https://leetcode.com/problems/maximum-width-ramp/discuss/265765/Detailed-Explaination-of-all-the-three-approaches


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM