LeetCode 769 — Max Chunks To Make Sorted (Java)
Approach: Greedy — track running maximum
The array is a permutation of [0, n-1]. A chunk [0…i] can be split off exactly when the maximum value seen so far equals the index i. At that point, all values 0…i are contained in the prefix, so it can be sorted independently and forms one valid chunk.
class Solution {
public int maxChunksToSorted(int[] arr) {
int chunks = 0;
int max = 0;
for (int i = 0; i < arr.length; i++) {
max = Math.max(max, arr[i]);
if (max == i) { // prefix [0..i] contains exactly values 0..i
chunks++;
}
}
return chunks;
}
}
Complete Runnable Example
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.maxChunksToSorted(new int[]{4,3,2,1,0})); // 1
System.out.println(sol.maxChunksToSorted(new int[]{1,0,2,3,4})); // 4
System.out.println(sol.maxChunksToSorted(new int[]{0,1,2,3})); // 4
System.out.println(sol.maxChunksToSorted(new int[]{2,0,1})); // 1
System.out.println(sol.maxChunksToSorted(new int[]{0})); // 1
}
}
Walkthrough — arr = [1, 0, 2, 3, 4]
i arr[i] max max == i? chunks
0 1 1 no 0
1 0 1 yes 1
2 2 2 yes 2
3 3 3 yes 3
4 4 4 yes 4
Result: 4 ✓ (chunks: [1,0], [2], [3], [4])
Walkthrough — arr = [4,3,2,1,0]
i arr[i] max max == i? chunks
0 4 4 no 0
1 3 4 no 0
2 2 4 no 0
3 1 4 no 0
4 0 4 yes 1
Result: 1 ✓
Complexity
Metric Complexity
Time O(n) — single pass
Space O(1)
Key Points
- Permutation property is crucial — because arr contains exactly 0…n-1, the prefix [0…i] is independently sortable iff its maximum is i. All values 0…i are guaranteed to be present in that prefix.
- Greedy cut is optimal — cutting as early as possible (whenever max == i) maximizes the number of chunks.
- Contrast with 768 — in Max Chunks To Make Sorted II, elements may be duplicated or unsorted, so you’d need a prefix-max vs. sorted-prefix-min comparison (or monotonic stack). Here the permutation constraint reduces it to a single running max.
- Single pass, O(1) extra space — no sorting, no auxiliary arrays.
Why not just compare arr[i] == i?
Because a chunk may be larger than one element. [1, 0] has neither element equal to its index, but the whole chunk is valid. The running-max trick correctly handles that: at i = 1, max = 1 == i, so we cut.
Optional: (For reference only) version without the permutation assumption
If you ever need a variant that works on arbitrary arrays (i.e., LeetCode 768), the idea changes — but for this problem the above is the canonical, optimal solution.

本文详解LeetCode 769题‘Max Chunks To Make Sorted’的Java实现,利用数组为[0,n-1]排列的特性,通过贪心策略维护运行最大值,当max==i时切分一个有效块。时间复杂度O(n),空间复杂度O(1)。核心在于理解排列性质如何保证前缀包含全部0..i值,从而支持独立排序。
212

被折叠的 条评论
为什么被折叠?



