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).
excellent post. Full Stack Training In Pune
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.
https://www.besanttechnologies.com/amazon-web-services-training-in-pune
http://www.trainingpune.in/aws-training-in-pune.html
why maintain the minimum value?