769. Max Chunks To Make Sorted

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了769. Max Chunks To Make Sorted相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    // O(n)
    // The idea is to maintain a window for all chars seen so far.
    // For [1,0,2,3,4], i = 0, we know the window should at least end on pos[i=0]=1.
    // For [4,3,2,1,0], i = 0, we know the window should at least end on pos[i=0]=4.
    // Then we move to next char in original string, and extend the window if necessary, 
    // until i==w. So then we need to move to next window.
    // We don‘t need to maintain the window start position.
    int maxChunksToSorted(vector<int>& arr) {
        int w = 0, res = 0;
        for (int i = 0; i < arr.size(); i++) {
            w = max(w, arr[i]);
            if (i == w) {
                res++;
                w = i+1;
            }
        }
        return res;
    }
};

 

以上是关于769. Max Chunks To Make Sorted的主要内容,如果未能解决你的问题,请参考以下文章

769. Max Chunks To Make Sorted

Max Chunks To Make Sorted LT769

769. Max Chunks To Make Sorted

leetcode 769. Max Chunks To Make Sorted 最多能完成排序的块(中等)

Max Chunks To Make Sorted

768. Max Chunks To Make Sorted II