Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2085967/Python-Explanation-with-pictures-stack
- Logic:
- arr[i] will be removed the nearest greater element in left.
- We will maintain a decreasing stack of pair where first element is element of array
- and second element will be the steps required to remove that element.
- An element will be only removed if all the element between current element and left greater
- element will be removed.so the steps required to remove current element is maximum steps
- required to remove all the smaller elements between current and left greater element+1.
- */
- class Solution {
- public:
- int totalSteps(vector<int>& arr) {
- stack<pair<int,int>> st;
- st.push({arr[0],0});
- int ans=0;
- for(int i=1;i<arr.size();i++){
- int cnt=0;
- while(!st.empty() && arr[i]>=st.top().first){
- cnt=max(st.top().second,cnt);
- st.pop();
- }
- if(st.empty()) cnt=0; //This means that no greater element in left,so no one will remove it.
- else cnt+=1;
- ans=max(cnt,ans);
- st.push({arr[i],cnt});
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement