# 769. Max Chunks To Make Sorted 最多能完成排序的块

@TOC

## # 题目描述

Given an array `arr` that is a permutation of `[0, 1, ..., arr.length - 1]`, we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

Example 1:

``````Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.
``````

Example 2:

``````Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.
``````

Note:

1. arr will have length in range [1, 10].
2. arr[i] will be a permutation of [0, 1, ..., arr.length - 1].

## # 解题方法

``````对于：[1,0,2,3,4]

1       目前最大值1，index = 0， 不可划分
0       目前最大值1，index = 1， 可划分
2       目前最大值2，index = 2， 可划分
3       目前最大值3，index = 3， 可划分
4       目前最大值3，index = 4， 可划分
``````

``````class Solution:
def maxChunksToSorted(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
chunks = 0
pre_max = 0
for i, num in enumerate(arr):
if num > pre_max:
pre_max = num
if pre_max == i:
chunks += 1
return chunks
``````

``````class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
const int N = arr.size();
int res = 0;
int preMax = 0;
for (int i = 0; i < N; i++) {
if (arr[i] > preMax)
preMax = arr[i];
if (i == preMax)
res++;
}
return res;
}
};
``````

## # 日期

2018 年 5 月 28 日 —— 太阳真的像日光灯～ 2018 年 12 月 18 日 —— 改革开放40周年