码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode]376. Wiggle Subsequence

时间:2018-01-24 16:57:18      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:example   ret   its   return   alt   first   hat   one   let   

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<int>& 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 };

 

[Leetcode]376. Wiggle Subsequence

标签:example   ret   its   return   alt   first   hat   one   let   

原文地址:https://www.cnblogs.com/David-Lin/p/8342030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!