其他分享
首页 > 其他分享> > Leetcode 2289. Steps to Make Array Non-decreasing (单调栈)

Leetcode 2289. Steps to Make Array Non-decreasing (单调栈)

作者:互联网

题目

题解:

class Solution {
public:
    
    int s[100005];
    int dp[100005];
    int totalSteps(vector<int>& nums) {
     
        int ans =0;
        s[0] = 0;
        dp[0]=0;
        int pos =0;
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i]<nums[s[pos]])
            {
                ans = max(ans, 1);
                dp[i] = 1;
                s[++pos] = i;
            }
            else
            {
                int x = 0;
                while(pos!= -1 && nums[i]>=nums[s[pos]])
                {
                    x = max(x, dp[s[pos]]); 
                    pos--;          
                }
                
                if(pos == -1)
                {
                    dp[i] = 0;
                }
                else
                {
                    dp[i] = x + 1;
                    ans = max(ans, dp[i]);
                }
                
                s[++pos] = i; 
            }
            
        }
        return ans;
    }
};

标签:2289,Non,int,左边,Make,元素,pos,ans,dp
来源: https://www.cnblogs.com/dacc123/p/16341107.html