给定一个允许出现重复元素的数组,判断最多可以分成多少段,使得段与段之间都是有序的
class Solution {
public int maxChunksToSorted(int[] arr) {
if(arr.length<2)return arr.length;
int max = Integer.MIN_VALUE,count = 0;
//get index array like [1,2,3] or [5,2,2,3,1]
int[] sorted = arr.clone();
int[] newArr = new int[arr.length];
Arrays.sort(sorted);
int pre = -1;
for(int i=0;i<sorted.length;i++){
for(int j=0;j<arr.length;j++)
if(arr[j]==sorted[i] && (i==0 || sorted[i]!=sorted[i-1] || pre<j)){
newArr[j] = i;
pre = j;
break;
}
}
for(int i=0;i<arr.length;i++){
max = Math.max(max,newArr[i]);
if(max==i){
count++;
}
}
return count;
}
}
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
stack = [] # store a list of biggest element of each chunk
for n in arr:
m = n # the biggest element from beginning to n
while len(stack)>0 and stack[-1]>n:
m = max(m, stack.pop())
stack.append(m) # all element bigger than n was poped out of stack, so this is the biggest element
return len(stack) # length of the chunks array