Taro Logo

Max Chunks To Make Sorted

Medium
4 views
2 months ago

You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1]. 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 = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.

Example 2:

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

Constraints:

  • n == arr.length
  • 1 <= n <= 10
  • 0 <= arr[i] < n
  • All the elements of arr are unique.
Sample Answer
class Solution {
    public int maxChunksToSorted(int[] arr) {
        int n = arr.length;
        int max = 0;
        int count = 0;

        for (int i = 0; i < n; i++) {
            max = Math.max(max, arr[i]);
            if (max == i) {
                count++;
            }
        }

        return count;
    }
}

Explanation:

The problem asks us to find the maximum number of chunks we can split an array into such that when we sort each chunk individually and concatenate them, we get the sorted array.

We iterate through the array, keeping track of the maximum value seen so far. If at any point, the maximum value seen so far is equal to the index, then we can split the array into a chunk at that index.

For example, consider the array [1,0,2,3,4].

  • At index 0, max = 1. Since 1 != 0, we cannot split here.
  • At index 1, max = 1. Since 1 == 1, we can split into [1,0]
  • At index 2, max = 2. Since 2 == 2, we can split into [1,0], [2]
  • At index 3, max = 3. Since 3 == 3, we can split into [1,0], [2], [3]
  • At index 4, max = 4. Since 4 == 4, we can split into [1,0], [2], [3], [4]

Thus, the maximum number of chunks is 4.

Big(O) Time Complexity:

The time complexity is O(n) because we iterate through the array once.

Big(O) Space Complexity:

The space complexity is O(1) because we only use a few constant extra variables.