769. Max Chunks To Make Sorted #973
-
Topics: You are given an integer array We split Return the largest number of chunks we can make to sort the array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the largest number of chunks that can be formed such that each chunk can be sorted individually, and when concatenated, the result is the sorted version of the entire array. Approach:
Let's implement this solution in PHP: 769. Max Chunks To Make Sorted <?php
/**
* @param Integer[] $arr
* @return Integer
*/
function maxChunksToSorted($arr) {
$n = count($arr);
$maxSoFar = -1;
$chunks = 0;
// Traverse through the array
for ($i = 0; $i < $n; $i++) {
// Update the max value encountered so far
$maxSoFar = max($maxSoFar, $arr[$i]);
// If the maximum value encountered so far equals the current index
// It means we can split here, making a chunk.
if ($maxSoFar == $i) {
$chunks++;
}
}
return $chunks;
}
// Test cases
$arr1 = [4, 3, 2, 1, 0];
$arr2 = [1, 0, 2, 3, 4];
echo maxChunksToSorted($arr1); // Output: 1
echo "\n";
echo maxChunksToSorted($arr2); // Output: 4
?> Explanation:
Time Complexity:
Example Walkthrough:For
Thus, the output for this case is |
Beta Was this translation helpful? Give feedback.
We need to find the largest number of chunks that can be formed such that each chunk can be sorted individually, and when concatenated, the result is the sorted version of the entire array.
Approach:
Key Observation:
0
ton-1
. The idea is to traverse the array and find positions where the chunks can be separated.Strategy:
i
, check if the maximum value up toi
is less than or e…