Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2289. Steps to Make Array Non-decreasing #176

Open
Woodyiiiiiii opened this issue Jan 13, 2023 · 0 comments
Open

Leetcode 2289. Steps to Make Array Non-decreasing #176

Woodyiiiiiii opened this issue Jan 13, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题我的想法是,一个数组中维护多个stack,最后合并,但这样写出来肯定不对,所以该用数组dp来存储,dp[i]表示能i位置能吞并的最大值。

其次,关键是iterate reversely

然后维护一个单调栈

class Solution {
    public int totalSteps(int[] nums) {
        int n = nums.length, ans = 0;
        int[] dp = new int[n];
        LinkedList<Integer> stack = new LinkedList<>();
        for (int i = n - 1; i >= 0; --i) {
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
                dp[i] = Math.max(++dp[i], dp[stack.pop()]);
                ans = Math.max(ans, dp[i]);
            }
            stack.push(i);
        }
        return ans;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant