Problem 507
Max Chunks to Make Sorted
Medium · 20 pts · Array, Greedy
Problem
The array is a permutation of the numbers 0 to N - 1. Split it into consecutive chunks, sort each chunk on its own, and join the chunks back together in order. Find the largest number of chunks for which the result is the fully sorted array. A chunk can end at position i exactly when the largest value seen so far equals i, because then the first i + 1 positions hold exactly the values 0 to i.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. The values are a permutation of 0 to N - 1.
Output
Print the maximum number of chunks.
Constraints
1 <= N <= 100000; A is a permutation of 0 .. N-1
Example input
5 1 0 2 3 4
Example output
4
Explanation
In 1 0 2 3 4, the chunks [1 0], [2], [3] and [4] each sort into place: 0 1 2 3 4. That is 4 chunks, and 1 and 0 cannot be separated.