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.

Analysis

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) {
    if(arr==null||arr.length==0){
        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];
 
        while(!stack.isEmpty()){
            int[] top = stack.peek();
 
            if(arr[i] < top[1]){
                min=Math.min(top[0], min);
                max=Math.max(max, top[1]);
                stack.pop();
            }else{
                break;
            }
        }
 
        stack.push(new int[]{min,max});
    }
 
    return stack.size();
}

Time complexity is O(n).

3 thoughts on “LeetCode – Max Chunks To Make Sorted (Java)”

Leave a Comment