Leetcode 769. Max Chunks To Make Sorted
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.
[0, 1, 2, ..., arr.length - 1]
?
arr
is in the range [1, 10^4]
.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:
max_so_far
set to a very low value and a chunk_count
initialized to 0.max_so_far
with the maximum value encountered up to the current index.max_so_far
is equal to the current index i
, increment chunk_count
by 1 because we found a valid chunk.chunk_count
after finishing the loop.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:
max_so_far
keeps track of the maximum value found as we iterate through the array.max_so_far
equals the current index, it signifies that the current segment can be considered as a chunk.This approach ensures we appropriately determine the maximum number of chunks that can be sorted independently to form the entire sorted array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?