博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Wiggle Subsequence
阅读量:4678 次
发布时间:2019-06-09

本文共 1619 字,大约阅读时间需要 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.

Examples:

Input: [1,7,4,9,2,5]Output: 6The entire sequence is a wiggle sequence.Input: [1,17,5,10,13,15,10,5,16,8]Output: 7There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].Input: [1,2,3,4,5,6,7,8,9]Output: 2

 

Follow up:

Can you do it in O(n) time?

 

Runtime: 0ms. 

1 class Solution { 2 public: 3     int wiggleMaxLength(vector
& nums) { 4 int positive = 1, negative = 1, n = nums.size(); 5 for(int i = 1; i < nums.size(); i++) { 6 if(nums[i] > nums[i - 1]) positive = negative + 1; 7 else if(nums[i] < nums[i - 1]) negative = positive + 1; 8 } 9 return min(n, max(positive, negative));10 }11 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/5743419.html

你可能感兴趣的文章
Qt 程序运行图标
查看>>
matlab Cplex使用
查看>>
(转)[unity3d]easytouch的使用
查看>>
Pascal's Travels
查看>>
Microsoft 家族新成员 Datazen 移动BI 介绍
查看>>
linq to entity GroupBy多个字段
查看>>
php中mysqli 处理查询结果集的几个方法
查看>>
二叉树遍历 空间复杂度为O(1)
查看>>
关于排序
查看>>
bzoj 3874: [Ahoi2014&Jsoi2014]宅男计划
查看>>
记录-Hibernate+servlet实现简单的增、删、查、改
查看>>
Uncaught TypeError: Cannot read property 'length' of null
查看>>
正在学习的路上
查看>>
又识用例图
查看>>
面试题思考: 什么是事务(ACID)?
查看>>
C# 实现保留两位小数的方法
查看>>
web前端面试的自我介绍
查看>>
朴素贝叶斯算法的实例
查看>>
Immunity Debugger
查看>>
Redis学习(8)-redis其他特性
查看>>