[Leetcode]376. Wiggle Subsequence
阿新 • • 發佈:2018-01-24
() ict cond numbers del pan main ini from is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast,
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]
[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