DEV Community

Hector Williams
Hector Williams

Posted on

768. Max Chunks To Make Sorted II

Problem
You are given an integer array arr.

We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return the largest number of chunks we can make to sort the array.

Example 1:

Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:

Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.

Constraints:

1 <= arr.length <= 2000
0 <= arr[i] <= 108

Discussion
This can be solved by traversing the array twice. The first time we put the elements in a min-heap/priority queue. This ensures that we have a list of the elements sorted in ascending order. Then we create 3 integer variables. One stores the sum of the sorted elements in the heap and is named sum. The second stores the total of the elements traversed in the array and is named total. The third stores the maximum number of chunks and is named answer.

We then traverse the array for the second time. We pull the topmost element from the heap and add it to sum. We add the element at the current index in the array and add to total. If the values are equal, we increment answer. Once we have traversed the array, we return the value of answer.

Solution
Java

class Solution {
    public int maxChunksToSorted(int[] arr) {
     PriorityQueue<Integer> pq=new PriorityQueue<>();
     int total=0;
     int sum=0;
     int answer=0;
     for(int i=0;i<arr.length;i++)pq.offer(arr[i]);
     for(int i=0;i<arr.length;i++){
      sum+=pq.poll();
      total+=arr[i];
      if(sum==total)answer++;  
     }
     return answer;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)