LeetCode – Max Chunks To Make Sorted (Java)

Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

For example, given [2,0,1], the method returns 0, as there can only be one chunk.


The key to solve this problem is using a stack to track the existing chunk. Each chunk is represented a min and max number. Each chunk is essentially an interval and the interval can not overlap.

Java Solution

public int maxChunksToSorted(int[] arr) {
        return 0;
    // use [min,max] for each chunk
    Stack<int[]> stack = new Stack<int[]>();
    for(int i=0; i<arr.length; i++){
        int min=arr[i];
        int max=arr[i];
            int[] top = stack.peek();
            if(arr[i] < top[1]){
                min=Math.min(top[0], min);
                max=Math.max(max, top[1]);
        stack.push(new int[]{min,max});
    return stack.size();

Time complexity is O(n).

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Kishore Srinivas

    why maintain the minimum value?