larscheng / algo

0 stars 0 forks source link

【Day 6 】2023-11-21 - 768. 最多能完成排序的块 II #7

Open larscheng opened 12 months ago

larscheng commented 12 months ago

https://leetcode-cn.com/problems/max-chunks-to-make-sorted-ii/ https://github.com/leetcode-pp/91alg-12-daily-check/issues/7

larscheng commented 12 months ago

思路

要保证最终合并后的序列整体升序,那么拆分出来的数组块之间,必须要为递增趋势

结合单调栈:找下一个大于xxx、下一个小于xxx的思路.
保证最终留在栈内的都是每一轮寻找的最大值,栈的大小即为最大拆分块数

单调栈:栈内元素有序,出栈顺序升序为单调递增栈,出栈顺序降序为单调递减栈.

构造单调栈的过程:https://lucifer.ren/blog/2020/11/03/monotone-stack/ (推荐配合食用)

代码

class Solution {
    public int maxChunksToSorted(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        for (int num : arr) {
            if (stack.isEmpty() || stack.peek() <= num){
                stack.push(num);
            }else {
                int max = stack.pop();
                while (!stack.isEmpty() && stack.peek() > num) {
                    stack.pop();
                }
                stack.push(max);
            }
        }
        return stack.size();
    }
}

复杂度