classSolution { inthelper(vector<int>& A, vector<int>& st, int num){ int l = 0, r = st.size() - 1, res = INT_MAX; while(l <= r) { int m = (l + r) / 2; if(A[st[m]] >= num) { res = min(res, m); r = m - 1; } else l = m + 1; } return res; } public: intmaxWidthRamp(vector<int>& A){ int n = A.size(), res = 0; vector<int> st; for(int i = n - 1; i >= 0; i--) { if(!st.empty() and A[st.back()] >= A[i]) { int j = helper(A, st, A[i]); res = max(res, st[j] - i); } if(st.empty() or A[st.back()] < A[i]) st.push_back(i); } return res; } };
classSolution { public: intmaxWidthRamp(vector<int>& nums){ int n = nums.size(); vector<pair<int, int>> A; set<int> s; for(int i = 0; i < n; i++) { s.insert(i); A.push_back({nums[i], i}); }
sort(begin(A), end(A)); int res = 0;
for(auto& [_, idx]: A) { res = max(res, *s.rbegin() - idx); s.erase(idx); }
return res; } };
monotonic stack solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intmaxWidthRamp(vector<int>& A){ int n = A.size(), res = 0; vector<int> st; for(int i = 0; i < n; i++) { if(st.empty() or A[st.back()] > A[i]) st.push_back(i); } for(int i = n - 1; i >= 0; i--) { while(!st.empty() and A[st.back()] <= A[i]) { res = max(res, i - st.back()); st.pop_back(); } } return res; } };