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 stack = new Stack();   for(int i=0; i

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:
<pre><code>
String foo = "bar";
</code></pre>
• cathryn leno

Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.

• Kishore Srinivas

why maintain the minimum value?