Leetcode 1002 Solution

This article provides solution to leetcode question 1002 (maximum-width-ramp)

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

Solution

class Solution {
public:
    int maxWidthRamp(vector<int>& A) {
        vector<pair<int, int>> pos;

        for (int i = 0; i < A.size(); i++)
            pos.push_back(make_pair(A[i], i));

        sort(pos.begin(), pos.end());

        int prev_max = -100000;
        int res = 0;

        for (auto it = pos.rbegin(); it != pos.rend(); it++)
        {
            int index = it->second;

            if (index < prev_max)
                res = max(prev_max - index, res);
            else
                prev_max = index;
        }

        return res;
    }
};