当前位置:网站首页>768. 最多能完成排序的块 II 贪心
768. 最多能完成排序的块 II 贪心
2022-07-27 01:49:00 【钰娘娘】
768. 最多能完成排序的块 II
这个问题和“最多能完成排序的块”相似,但给定数组中的元素可以重复,输入数组最大长度为
2000,其中的元素最大为10**8。
arr是一个可能包含重复元素的整数数组,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。我们最多能将数组分成多少块?
示例 1:
输入: arr = [5,4,3,2,1] 输出: 1 解释: 将数组分成2块或者更多块,都无法得到所需的结果。 例如,分成 [5, 4], [3, 2, 1] 的结果是 [4, 5, 1, 2, 3],这不是有序的数组。示例 2:
输入: arr = [2,1,3,4,4] 输出: 4 解释: 我们可以把它分成两块,例如 [2, 1], [3, 4, 4]。 然而,分成 [2, 1], [3], [4], [4] 可以得到最多的块数。注意:
arr的长度在[1, 2000]之间。arr[i]的大小在[0, 10**8]之间。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/max-chunks-to-make-sorted-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
做题结果
成功,还是错了1次,不细心
方法:贪心
1. 先后缀算下后面的最小值
2. 如果当前段的最大值小于等于后续的最小值,则说明此段落可以分割为单独一段
class Solution {
public int maxChunksToSorted(int[] arr) {
int ans = 0;
int n = arr.length;
int[] next = new int[n];
next[n-1]=arr[n-1];
for(int i = n-2; i >= 0; i--){
next[i] = Math.min(arr[i],next[i+1]);
}
int max = 0;
for(int i = 0; i < arr.length; i++){
max = Math.max(max,arr[i]);
if(i==n-1||next[i+1]>=max)++ans;
}
return ans;
}
}边栏推荐
- PIP3 setting alicloud
- Data Lake (20): Flink is compatible with iceberg, which is currently insufficient, and iceberg is compared with Hudi
- 关于OpenFeign的源码分析
- Safe-arc/warner power supply maintenance xenon lamp power supply maintenance analysis
- 太强了,一个注解搞定接口返回数据脱敏
- 最大连续子序列(DAY 77)
- [从零开始学习FPGA编程-54]:高阶篇 - 基于IP核的FPGA开发-PLL锁相环IP核的原理与配置(Altera)
- Idea 中添加支持@Data 插件
- Comprehensive care analysis lyriq Ruige battery safety design
- 将幕布文章OPML转换为Markdown的方法
猜你喜欢

注解@Autowired和@Resource的区别总结

Activiti5.22.0 extension supports domestic databases, taking gbase database as an example

Graphic SQL, this is too vivid!

客户案例 | 关注老年用户体验,银行APP适老化改造要避虚就实

Byte side: can TCP and UDP use the same port?

Deep learning vocabulary embedded, beam search

数据库概论 - MySQL的简单介绍

MySQL:互联网公司常用分库分表方案汇总

Indexing best practices

Detailed explanation of const usage in C language
随机推荐
客户案例 | 关注老年用户体验,银行APP适老化改造要避虚就实
How to design the red table of database to optimize the performance
Spark Learning Notes (V) -- spark core core programming RDD conversion operator
[机缘参悟-52]:交浅言深要因人而异
食物链(DAY 79)
Learn the recycling mechanism of recyclerview again
What are "full five unique" and "full two unique"? Any difference?
spark:地区广告点击量排行统计(小案例)
Explain
图解 SQL,这也太形象了吧!
Idea 中添加支持@Data 插件
字节一面:TCP 和 UDP 可以使用同一个端口吗?
Submodule cache cache failure
代码审查金字塔
Activiti5.22.0扩展支持达国产数据库,以GBase据库为例
围圈报数(北理工机试题)(DAY 83)
深度学习——词汇embedded、Beam Search
“date: write error: No space left on device”解决
[从零开始学习FPGA编程-54]:高阶篇 - 基于IP核的FPGA开发-PLL锁相环IP核的原理与配置(Altera)
Details of impala implementation plan