algoadvance

Leetcode 769. Max Chunks To Make Sorted

Problem Statement

You are given an array of integers arr which represents a permutation of the first n positive integers, where n is the array’s length. You need to partition the array into a maximum number of “chunks” (partitions), which can be individually sorted, and after concatenating them, the entire array returns to being sorted in increasing order.

Return the maximum number of chunks we can partition the array into.

Example

  1. Input: arr = [4,3,2,1,0] Output: 1
  2. Input: arr = [1,0,2,3,4] Output: 4

Constraints

Clarifying Questions

  1. Can the array have negative numbers?
    No, the array consists of the first n positive integers (including zero).
  2. Is the input guaranteed to be a permutation of the first n positive integers?
    Yes.

Strategy

To determine the maximum number of chunks, we can use a greedy algorithm. The key observation is that we can form a chunk ending at index i if the maximum value of the elements in the chunk so far is i. This ensures that all numbers up to i have appeared in the segment, and thus it can be sorted independently.

Here’s a step-by-step strategy:

  1. Initialize max_so_far to 0 and count_chunks to 0.
  2. Iterate through the array.
  3. For each index i, update max_so_far to be the maximum value observed so far.
  4. If max_so_far equals the current index i, it means all values up to i have been encountered, and we can form a chunk ending at index i. Increment the chunk counter.
  5. Return count_chunks at the end.

Code

Here’s the implementation of the strategy in Java:

public class Solution {
    public int maxChunksToSorted(int[] arr) {
        int maxSoFar = 0;
        int countChunks = 0;

        for (int i = 0; i < arr.length; i++) {
            maxSoFar = Math.max(maxSoFar, arr[i]);
            if (maxSoFar == i) {
                countChunks++;
            }
        }
        
        return countChunks;
    }
}

Explanation

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI