You are given an integer array arr
.
We split arr
into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
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.
Constraints:
1 <= arr.length <= 2000
0 <= arr[i] <= 108
题目链接:https://leetcode.com/problems/max-chunks-to-make-sorted-ii/
题目大意:给一个数组,求最多可以分成多少块,使得每块排完序后拼起来是单调递增的
题目分析:我的做法是对每个点找到距离其右边最远的小于它的位置,然后判断当前点是否为某一段的终点,且该终点为当前向右延伸的最远点,如果是则可以在此处进行一次切分
时间复杂度是n^2的,比较挫
11ms,时间击败7%
class Solution {
public int maxChunksToSorted(int[] arr) {
int n = arr.length;
int ed[] = new int[n];
for (int i = 0; i < n; i++) {
int j = n - 1;
while (j > i && arr[j] >= arr[i]) {
j--;
}
ed[i] = j;
}
int ans = 0, ma = 0;
for (int i = 0; i < n; i++) {
ma = Math.max(ed[i], ma);
if (ed[i] == i && ed[i] == ma) {
ans++;
}
}
return ans;
}
}
比较好的做法是维护从左往右的最大值和从右往左的最小值,如果leftMax[i] <= rightMin[i + 1],则显然左侧可以被切成一段