LeetCode-768. Max Chunks To Make Sorted II [C++][Java]

该博客主要解析LeetCode的一道算法题,题目要求在不改变数组元素顺序的前提下,找出将数组分割成若干连续子数组并排序后,最多能分割成多少个有序块。文章提供了C++和Java两种语言的解决方案,通过维护最大值和最小值数组来求解问题。
摘要由CSDN通过智能技术生成

LeetCode-768. Max Chunks To Make Sorted II icon-default.png?t=M3C8https://leetcode.com/problems/max-chunks-to-make-sorted-ii/

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] <= 10^8

【C++】

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        vector<int> mx = arr, mi = arr;
        for (int i = 1 ; i < arr.size(); i++) {mx[i] = max(arr[i] , mx[i-1]);}
        for (int i = arr.size() - 2; i >= 0; i--) {mi[i] = min(arr[i] , mi[i+1]);}
        int res = 1;
        for (int i = 0; i < arr.size() - 1; i++) {if(mx[i] <= mi[i+1]) {res++;}}
        return res;
    }
};

【Java】

class Solution {
    public int maxChunksToSorted(int[] arr) {
        int[] mx = arr.clone(), mi = arr.clone();
        for (int i = 1 ; i < arr.length; i++) {mx[i] = Math.max(arr[i] , mx[i-1]);}
        for (int i = arr.length - 2; i >= 0; i--) {mi[i] = Math.min(arr[i] , mi[i+1]);}
        int res = 1;
        for (int i = 0; i < arr.length - 1; i++) {if(mx[i] <= mi[i+1]) {res++;}}
        return res;
    }
}

参考文献

【1】复制对象clone(深复制和浅复制)_xiaoxiang-chen的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值