当前位置:网站首页>最长摆动序列[贪心练习]
最长摆动序列[贪心练习]
2022-07-05 20:42:00 【REN_林森】
前言
贪心/动态规划/单调栈,都是考察逻辑能力的一类高级题目,这些题需要分析,需要较好的变通能力。
一、最长摆动序列

二、贪心算法
1、贪心需要满足的条件
最优子结构:规模较大的问题的解由规模较小的子问题的解组成,规模较大的问题的解只由其中一个规模较小的子问题的解决定;
无后效性:后面阶段的求解不会修改前面阶段已经计算好的结果;
贪心选择性质:从局部最优解可以得到全局最优解。
注:其中对无后效性的把握尤为重要。贪心算法就是做出当前状态下的最优选择认为就可以解决问题。
2、思路分析
该题,只需要顺序找到峰和谷就行了,以高峰低谷作为摆动的节点,其体系那贪最值问题。
3、code
package everyday.greed;
public class WiggleMaxLength {
/* target:找最长摆动子序列。 把非峰/谷元素删掉即可,但是这里只需要统计最长摆动序列的长度,而不是最长摆动序列的元素,所以只计算峰/谷节点数,相当于变相删了其他非峰/谷节点。 */
public int wiggleMaxLength(int[] nums) {
if (nums.length < 2) return nums.length;
// 核心:只要最高峰/最低谷的元素,即最大最小值,摆动起来。
int curDiff = 0, preDiff = 0, ans = 1;
for (int i = 0; i < nums.length - 1; i++) {
curDiff = nums[i + 1] - nums[i];
// 计算峰 || 计算谷
if (curDiff > 0 && preDiff <= 0 || curDiff < 0 && preDiff >= 0) {
++ans;
preDiff = curDiff;
}
}
return ans;
}
}
总结
1)贪心练习。
参考文献
[1] LeetCode 最长摆动序列
边栏推荐
- 教你自己训练的pytorch模型转caffe(三)
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- Applet project structure
- Norgen AAV extractant box instructions (including features)
- Applet event binding
- 产品好不好,谁说了算?Sonar提出分析的性能指标,帮助您轻松判断产品性能及表现
- Abnova maxpab mouse derived polyclonal antibody solution
- 欢迎来战,赢取丰厚奖金:Code Golf 代码高尔夫挑战赛正式启动
- 挖财商学院给的证券账户安全吗?可以开户吗?
- How to form standard interface documents
猜你喜欢

Applet global configuration

Duchefa丨S0188盐酸大观霉素五水合物中英文说明书

Duchefa s0188 Chinese and English instructions of spectinomycin hydrochloride pentahydrate

Interpreting the daily application functions of cooperative robots

Abnova丨培养细胞总 RNA 纯化试剂盒中英文说明书

Abnova total RNA Purification Kit for cultured cells Chinese and English instructions

phpstudy小皮的mysql点击启动后迅速闪退,已解决

Make Jar, Not War

Norgen AAV extractant box instructions (including features)

Duchefa cytokinin dihydrozeatin (DHZ) instructions
随机推荐
The Chinese Academy of Management Sciences gathered industry experts, and Fu Qiang won the title of "top ten youth" of think tank experts
Abnova CRISPR spcas9 polyclonal antibody protocol
National Eye Care Education Conference, 2022 the Fourth Beijing International Youth eye health industry exhibition
Abnova fluorescent dye 620-m streptavidin scheme
3.3 project evaluation
Duchefa p1001 plant agar Chinese and English instructions
CVPR 2022 | common 3D damage and data enhancement
Abnova blood total nucleic acid purification kit pre installed relevant instructions
MySQL InnoDB架构原理
Abbkine BCA法 蛋白质定量试剂盒说明书
小程序事件绑定
Typhoon is coming! How to prevent typhoons on construction sites!
Duchefa丨D5124 MD5A 培养基中英文说明书
Ros2 topic [01]: installing ros2 on win10
1、强化学习基础知识点
Abnova丨 MaxPab 小鼠源多克隆抗体解决方案
Monorepo管理方法论和依赖安全
How to open an account online for futures? Is it safe?
Propping of resources
Abnova cyclosporin a monoclonal antibody and its research tools