根据题目,我们可以发现,从左到右,每个分块都有一个最大值,并且这些分块的最大值呈单调递增(非严格递增)。我们可以用一个栈来存储这些分块的最大值。最后得到的栈的大小,也就是题目所求的最多能完成排序的块。
时间复杂度
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
stk = []
for v in arr:
if not stk or v >= stk[-1]:
stk.append(v)
else:
mx = stk.pop()
while stk and stk[-1] > v:
stk.pop()
stk.append(mx)
return len(stk)
class Solution {
public int maxChunksToSorted(int[] arr) {
Deque<Integer> stk = new ArrayDeque<>();
for (int v : arr) {
if (stk.isEmpty() || stk.peek() <= v) {
stk.push(v);
} else {
int mx = stk.pop();
while (!stk.isEmpty() && stk.peek() > v) {
stk.pop();
stk.push(mx);
return stk.size();
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
stack<int> stk;
for (int& v : arr) {
if (stk.empty() || stk.top() <= v)
stk.push(v);
else {
int mx = stk.top();
stk.pop();
while (!stk.empty() && stk.top() > v) stk.pop();
stk.push(mx);
return stk.size();
func maxChunksToSorted(arr []int) int {
var stk []int
for _, v := range arr {
if len(stk) == 0 || stk[len(stk)-1] <= v {
stk = append(stk, v)
} else {
mx := stk[len(stk)-1]
stk = stk[:len(stk)-1]
for len(stk) > 0 && stk[len(stk)-1] > v {
stk = stk[:len(stk)-1]
stk = append(stk, mx)
return len(stk)
function maxChunksToSorted(arr: number[]): number {
const stack = [];
for (const num of arr) {
if (stack.length !== 0 && num < stack[stack.length - 1]) {
const max = stack.pop();
while (stack.length !== 0 && num < stack[stack.length - 1]) {
stack.pop();
stack.push(max);
} else {
stack.push(num);
return stack.length;
impl Solution {
pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
let mut stack = vec![];
for num in arr.iter() {
if !stack.is_empty() && num < stack.last().unwrap() {
let max = stack.pop().unwrap();
while !stack.is_empty() && num < stack.last().unwrap() {
stack.pop();
stack.push(max);
} else {
stack.push(*num);
stack.len() as i32
comments | difficulty | edit_url |
---|