Advertisement
imashutosh51

Steps to make Array non-decreasing

Oct 8th, 2022
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. /*
  2. https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2085967/Python-Explanation-with-pictures-stack
  3.  
  4. Logic:
  5. arr[i] will be removed the nearest greater element in left.
  6. We will maintain a decreasing stack of pair where first element is element of array
  7. and second element will be the steps required to remove that element.
  8. An element will be only removed if all the element between current element and left greater
  9. element will be removed.so the steps required to remove current element is maximum steps
  10. required to remove all the smaller elements between current and left greater element+1.
  11.  
  12.  
  13. */
  14.  
  15.  
  16. class Solution {
  17. public:
  18.     int totalSteps(vector<int>& arr) {
  19.         stack<pair<int,int>> st;
  20.         st.push({arr[0],0});
  21.         int ans=0;
  22.         for(int i=1;i<arr.size();i++){
  23.             int cnt=0;
  24.             while(!st.empty() && arr[i]>=st.top().first){
  25.                 cnt=max(st.top().second,cnt);
  26.                 st.pop();
  27.             }
  28.             if(st.empty()) cnt=0;   //This means that no greater element in left,so no one will remove it.
  29.             else cnt+=1;
  30.             ans=max(cnt,ans);
  31.             st.push({arr[i],cnt});
  32.         }
  33.         return ans;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement