Skip to content

Latest commit

 

History

History

962

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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
 

Related Topics:
Array

Solution 1.

Consider the array ends with 4, 1, 2. For the a number n in front:

  • If n <= 2, we use the last 2 to form the ramp. The last 1 won't be used.
  • If 2 < n <= 4, we use the last 4 to form the ramp.

So we can traverse from rear to front, and save the numbers in ascending order:

numbers: [2, 4]
indexes: [N - 1, N - 3]

Then we traverse from front to rear, use lower_bound to find the smallest number greater than the current A[i]. The corresponding index can be used form a ramp.

// OJ: https://leetcode.com/problems/maximum-width-ramp/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
    int maxWidthRamp(vector<int>& A) {
        int N = A.size(), ans = 0;
        vector<int> v, index;
        for (int i = N - 1; i >= 0; --i) {
            if (v.empty() || v.back() < A[i]) {
                v.push_back(A[i]);
                index.push_back(i);
            }
        }
        for (int i = 0; i < N; ++i) {
            int ind = lower_bound(v.begin(), v.end(), A[i]) - v.begin();
            ans = max(ans, index[ind] - i);
        }
        return ans;
    }
};