LeetCode – 768. Max Chunks To Make Sorted II

本文解析了一种算法问题,即给定一个可能包含重复元素的整数数组,如何将其拆分成多个“块”,并对每个块进行排序,最终连接成一个有序数组。探讨了通过比较原数组和排序后数组的累加和来确定最优分区数量的方法。

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

This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.


Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

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.

Note:

  • arr will have length in range [1, 2000].
  • arr[i] will be an integer in range [0, 10**8].

题意:

给一个排列,可能有重复元素,我们将数组拆分成一些“块”(分区),并对每个块进行单独排序。连接它们之后,结果等于排序后的数组。问最多能够分成多少个分区(块)

分析:

这道题目的思路和LeetCode – 769. Max Chunks To Make Sorted一样,关键是找出划分合理chunk的条件。

因为有重复元素,可以考虑判断累加和的方式,排序后的数组前i个元素累加的和等于原数组前i个数累加的和时可以分为一个块~

具体实现如下:

public int name(int[] arr) {
	int sum1 = 0, sum2 = 0, ans = 0;
	int[] t = new int[arr.length];
	System.arraycopy(arr, 0, t, 0, arr.length);;
	Arrays.sort(t);
	for(int i = 0; i < arr.length; i++) {
		sum1 += t[i];
		sum2 += arr[i];
		if(sum1 == sum2) ans++;
	}
	return ans;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值