Question
Given an array arr of integers (not necessarily distinct), 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 = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn’t sorted.
Example 2:
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
Note:
arr will have length in range [1, 2000]. arr[i] will be an integer in range [0, 10**8].
Solution
对于数列arr来说,期望得到的结果是sorted(arr)。对于arr中的第k个位置,
arr[:k]
a
r
r
[
:
k
]
能构成一个chunk的条件是,
max(arr[:k])<min(arr[k+1:])
m
a
x
(
a
r
r
[
:
k
]
)
<
m
i
n
(
a
r
r
[
k
+
1
:
]
)
。
所以首先用一次逆序循环遍历arr,得到每个k所对应的
min(arr[k+1:])
m
i
n
(
a
r
r
[
k
+
1
:
]
)
,存储在一个和arr大小相同的列表中。再正序遍历arr,判断是否满足判决条件。
复杂度为O(2N)/O(N)。
完整代码如下:
import copy
class Solution:
def maxChunksToSorted(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
min_arr = copy.copy(arr)
min_num = arr[-1]
for i in range(len(arr)-1,-1,-1):
min_num = min(min_num,arr[i])
min_arr[i] = min(min_num,arr[i])
max_num = arr[0]
ans = 1 #如果没有元素满足判决条件,返回1
for i in range(len(arr)-1):
max_num = max(max_num,arr[i])
if max_num <= min_arr[i+1]:
ans += 1
print(min_arr)
return ans