768.最多能完成排序的块 II

This commit is contained in:
游由 2022-08-18 19:54:29 +08:00
parent d764340d0a
commit 474f6eb494
1 changed files with 20 additions and 2 deletions

View File

@ -33,7 +33,21 @@ impl Solution {
/// * 排序
/// * 单调栈
pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
unimplemented!()
let (mut max_vec, mut min_vec) = (vec![0; arr.len()], vec![0; arr.len()]);
let (mut max, mut min, mut ret) = (i32::MIN, i32::MAX, 1);
for i in 0..arr.len() {
let j = arr.len() - i - 1;
max = max.max(arr[i]);
min = min.min(arr[j]);
max_vec[i] = max;
min_vec[j] = min;
}
for i in 1..arr.len() {
if max_vec[i - 1] <= min_vec[i] {
ret += 1;
}
}
ret
}
}
@ -43,6 +57,10 @@ mod test {
#[test]
fn test_q0768() {
unimplemented!()
assert_eq!(Solution::max_chunks_to_sorted(vec![5, 4, 3, 2, 1]), 1);
assert_eq!(Solution::max_chunks_to_sorted(vec![2, 1, 3, 4, 4]), 4);
assert_eq!(Solution::max_chunks_to_sorted(vec![5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 10, 11]), 3);
assert_eq!(Solution::max_chunks_to_sorted(vec![0, 0, 1, 1, 1]), 5);
assert_eq!(Solution::max_chunks_to_sorted(vec![1, 0, 1, 3, 2]), 3);
}
}