Max Chunks To Make Sorted II

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

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

题目不复杂 能分割成两部分的充要条件就是前半部分的最大值要<=后半部分的最小值 我们用 maxes[i]来记录从 0 到 i 的最大值 然后用 mins[i]来记录从 arr.len()-1 到 i 的最小值。只要 maxes[i] <= mins[i+1], 那从 i 之后就可以进行分割



impl Solution {
    pub fn max_chunks_to_sorted(arr: Vec<i32>) -> i32 {
        let mut maxes = vec![0; arr.len()];
        maxes[0] = arr[0];
        for i in 1..arr.len() {
            maxes[i] = maxes[i - 1].max(arr[i]);
        }
        let mut mins = vec![0; arr.len() + 1];
        mins[arr.len()] = i32::MAX;
        for i in (0..arr.len()).rev() {
            mins[i] = mins[i + 1].min(arr[i]);
        }
        let mut ans = 0;
        for i in 0..arr.len() {
            if maxes[i] <= mins[i + 1] {
                ans += 1;
            }
        }
        ans
    }
}

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6