algoadvance

Leetcode 769. Max Chunks To Make Sorted

Problem Statement

Given an array arr that is a permutation of [0, 1, 2, ..., arr.length - 1], we need to find the maximum number of chunks we can split the array into such that after sorting each chunk individually and concatenating them, we obtain a sorted array.

Clarifying Questions

  1. Input Constraints:
    • Is the array guaranteed to be a permutation of [0, 1, 2, ..., arr.length - 1]?
      • Yes.
    • What is the length range of the array?
      • The length of arr is in the range [1, 10^4].
  2. Output:
    • Do we need to return the exact chunks or just the count of chunks?
      • We only need to return the count of chunks.

Strategy

To solve this problem, keep track of the maximum value encountered in the array as you iterate through it. If the maximum value at a certain index i is equal to i, it means you can form a chunk between the previous index (last chunk’s end) and i because all elements before and including i can be sorted independently of the subsequent elements while still maintaining the overall sorted order when concatenated.

Here’s a step-by-step approach:

  1. Initialize variables: Start with max_so_far set to a very low value and a chunk_count initialized to 0.
  2. Iterate through the array:
    • Update max_so_far with the maximum value encountered up to the current index.
    • If max_so_far is equal to the current index i, increment chunk_count by 1 because we found a valid chunk.
  3. Return the chunk_count after finishing the loop.

Time Complexity

Code

Here’s the C++ implementation for the given strategy:

#include <vector>
#include <algorithm> // For std::max

class Solution {
public:
    int maxChunksToSorted(std::vector<int>& arr) {
        int max_so_far = 0;
        int chunk_count = 0;
        
        for (int i = 0; i < arr.size(); ++i) {
            max_so_far = std::max(max_so_far, arr[i]);
            
            if (max_so_far == i) {
                ++chunk_count;
            }
        }
        
        return chunk_count;
    }
};

In the above code:

This approach ensures we appropriately determine the maximum number of chunks that can be sorted independently to form the entire sorted array.

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