博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode]376. Wiggle Subsequence
阅读量:6463 次
发布时间:2019-06-23

本文共 1651 字,大约阅读时间需要 5 分钟。

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

思路: 假设在下标为 i 的位置已经知道了前面最长wiggle subsequence 的值, 那么对于 i 这个位置wiggle subsequence 的值要么和前面一样,要么比之前多1;

1 class Solution { 2 public: 3     int wiggleMaxLength(vector
& nums) { 4 if (nums.size() <= 1) 5 return nums.size(); 6 int dp[nums.size()], diff = nums[1] - nums[0]; dp[0] = 1; 7 int flag = (diff > 0 ? -1 : 1); 8 for (int i = 1; i != nums.size(); ++i){ 9 diff = nums[i] - nums[i-1];10 if ((flag > 0 && diff > 0) || (flag < 0 && diff < 0) || !diff)11 dp[i] = dp[i-1];12 else {13 dp[i] = dp[i-1] + 1;14 flag = diff;15 }16 }17 return dp[nums.size() - 1];18 }19 };

 

转载于:https://www.cnblogs.com/David-Lin/p/8342030.html

你可能感兴趣的文章
windows 7/mac编译cocos2d-x-3.2*的android工程报错
查看>>
MYSQL导入导出.sql文件(转)
查看>>
使用Elasticsearch、Logstash、Kibana与Redis(作为缓冲区)对Nginx日志进行收集(转)
查看>>
git review报错一例
查看>>
Tomcat在Linux上的安装与配置
查看>>
《信息安全系统设计基础》 课程教学
查看>>
Linux平台下使用rman进行oracle数据库迁移
查看>>
全栈工程师学习Linux技术的忠告
查看>>
iOS自定制tabbar与系统的tabbar冲突,造成第一次点击各个item图片更换选中,第二次选中部分item图片不改变...
查看>>
C# Dictionary用法总结
查看>>
SVN服务器使用(二)
查看>>
反射获取内部类以及调用内部类方法
查看>>
C语言 - pthread
查看>>
谈Linq To Sql的优劣--纯个人观点
查看>>
HDU 4996 Revenge of LIS(DP)
查看>>
App里面如何正确显示用户头像
查看>>
DATAGUARD维护:从库宕机后如何恢复到管理恢复模式
查看>>
Android中的PID和UID
查看>>
U-BOOT之一:BootLoader 的概念与功能
查看>>
我的路上
查看>>