Max Chunks To Make Sorted II

给定一个整数数组,将其分割成若干部分并分别排序,最后合并应得到已排序的数组。目标是找到可以产生这种排序的最多分割数。关键在于比较每个位置的最大值和后一部分的最小值。代码实现中,使用maxes和mins数组分别存储前缀最大值和后缀最小值,如果maxes[i]小于或等于mins[i+1],则可以在位置i处进行分割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值