Max Chunks To Make Sorted
Split an array of the numbers 0 to n - 1 into as many pieces as possible, so that sorting each piece sorts the whole array.
You are given an array arr
Example 1
Output: 1
Explanation: the 4 at the front belongs at the end, so the only chunk that works is the whole array.
Example 2
Output: 4
Explanation: the chunks [1, 0], [2], [3] and [4] sort into [0, 1], [2], [3] and [4].
The Idea
Picture five numbered cards in a row: 1, 0, 2, 3, 4. You may split the row into groups of neighbouring cards, sort each group on its own, and leave the groups in their places. You want the row to end up as 0, 1, 2, 3, 4, with as many groups as possible. Splitting it into [1, 0], [2], [3] and [4] works: sorting [1, 0] gives [0, 1], and the other groups are already in order. So the answer is 4.
Example 1 is the opposite case. In [4, 3, 2, 1, 0] the 4 sits at the front, but it belongs at the end. Sorting a group never moves a card into another group, so the 4 can only reach the end if its group runs to the end. The whole row has to be one group, and the answer is 1.
So where may we cut? A cut after a position is fine only when every card to its left belongs on the left. In Example 2, counting positions from 0, after position 1 the left side holds 1 and 0. Those are exactly the cards that the sorted row puts at positions 0 and 1. After position 0, the left side holds only the 1, which belongs at position 1, on the other side of the cut.
How can we tell quickly that positions 0 to i hold exactly the numbers 0 to i? Look at the largest of them. Positions 0 to i hold i + 1 different numbers. If the largest is i, they can only be 0, 1, ..., i, because those are the only i + 1 numbers that are not bigger than i. Look at the picture below.
Under each card is the largest value so far. At position 0 it is 1, bigger than the position, so there is no cut there. At position 1 it is still 1, equal to the position, so a cut follows. After that each card is the new largest value and equals its position, so each one ends with a cut of its own. The last card needs no cut, because the array ends there.
So the whole problem comes down to one number carried from left to right: the largest value seen so far. Keeping that number while walking along an array is called a running maximum. Every position where it equals the position ends a chunk.
Solution Approach
Turning that idea into code means settling three things: which places allow a cut, how to test a place in one step, and why cutting at every allowed place gives the most chunks.
Places that allow a cut
Why not simply try every way of cutting? An array of n numbers has n - 1 gaps between neighbours, and each gap is either cut or not, which gives 2n - 1 ways. For 30 numbers that is more than 500 million splits, each to be sorted and checked.
Each gap can be judged on its own instead. Sorting a chunk only rearranges the numbers inside it, and the sorted array puts the number v at position v. So a cut after position i is allowed exactly when positions 0 to i already hold the numbers 0 to i, in any order.
Testing a place in one step
How do we check "positions 0 to i hold 0 to i" without sorting them each time? With the running maximum from the picture. The variable maxMath.maxmaxi
The last position always passes this test, because the largest number in the whole array is n - 1. That match counts the final chunk, so counting the matches counts the chunks.
Using every allowed place
Is it safe to cut at all the allowed places at once? Take two neighbouring cuts, after position i and after position j. The left side of the second cut holds 0 to j, and the left side of the first holds 0 to i. So the chunk between them holds exactly i + 1 to j, and sorting it puts each number in its place.
A cut anywhere else leaves some number on the wrong side, which no sorting can fix. So a valid split can only use allowed places, and using all of them gives the most chunks.
Java Solution
The method maxChunksToSorted
- First, set
, the number of chunks found so far, to 0, andchunks , the largest value seen so far, to 0.max - Walk along the array with one loop, moving
from the first position to the last. At each position, updatei withmax , so it holds the largest value in positions 0 toMath.max(max, arr[i]) .i - If
equalsmax , positions 0 toi hold exactly the numbers 0 toi , so a chunk ends here: add 1 toi .chunks - When the loop is done, return
.chunks
The main[2, 0, 1, 4, 3]
import java.util.Arrays;
public class MaxChunksToMakeSorted {
public static int maxChunksToSorted(int[] arr) {
int chunks = 0;
int max = 0;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]); // largest value in arr[0..i]
if (max == i) { // arr[0..i] holds exactly 0..i
chunks++;
}
}
return chunks;
}
public static void main(String[] args) {
int[][] inputs = {
{4, 3, 2, 1, 0},
{1, 0, 2, 3, 4},
{0},
{0, 1, 2, 3},
{2, 0, 1, 4, 3}
};
for (int[] arr : inputs) {
String shown = Arrays.toString(arr);
System.out.println(shown + " -> " + maxChunksToSorted(arr));
}
}
}
Running it prints:
[4, 3, 2, 1, 0] -> 1
[1, 0, 2, 3, 4] -> 4
[0] -> 1
[0, 1, 2, 3] -> 4
[2, 0, 1, 4, 3] -> 2
On [4, 3, 2, 1, 0]maxi[0, 1, 2, 3]
Look at the last line, 2. maxmaxi
Comparing each number with its own position, arr[i] == i[1, 0, 2, 3, 4][2, 0, 1, 4, 3]
Complexity
The work is a single pass over the array, keeping a count of chunks and the largest value so far.
- Time: O(n), because the loop visits each of the n positions once and does one
and one comparison there.Math.max - Space: O(1). Only
,chunks andmax are kept, and the array is only read, never copied or sorted.i