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;
    }
};
原文地址:https://www.cnblogs.com/JTechRoad/p/8973730.html