selected_coding_interview/docs/768. 最多能完成排序的块 II.md
排序块定义:
贪心法则 (划分出尽可能多的排序块):
[A]与 num 合并,形成新排序块[A | num],最大值仍为 $head$ ;[num] 。算法流程:
pop() 出栈,并保存栈顶值为 $head$ 。 (此情况下,新排序块最大值还为 $head$ ,因此先暂存)pop() 出栈。 (判断加入 $num$ 需要合并的所有排序块,每 pop() 一个 $head$ 代表合并一个块)push() 入栈。 (将 $head$ 重新加入,作为新排序块的最大值)push() 入栈。 (加入单个元素的新排序块 [num])复杂度分析:
图解中每一种颜色代表一个排序块。
<,,,,,,,,,,,,,,>
class Solution:
def maxChunksToSorted(self, arr: [int]) -> int:
stack = []
for num in arr:
if stack and num < stack[-1]:
head = stack.pop()
while stack and num < stack[-1]: stack.pop()
stack.append(head)
else: stack.append(num)
return len(stack)
class Solution {
public int maxChunksToSorted(int[] arr) {
LinkedList<Integer> stack = new LinkedList<Integer>();
for(int num : arr) {
if(!stack.isEmpty() && num < stack.getLast()) {
int head = stack.removeLast();
while(!stack.isEmpty() && num < stack.getLast()) stack.removeLast();
stack.addLast(head);
}
else stack.addLast(num);
}
return stack.size();
}
}