• [Leetcode]376. Wiggle Subsequence


    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 };
  • 相关阅读:
    Django form
    八月22日,django知识点总结:
    MVC其实很简单(Django框架)
    Django框架
    python实战(开发新浪微博应用)
    MySQL练习题
    MySQL练习题参考答案
    Python中用format函数格式化字符串
    harbor的nginx替换
    bash传参的使用记录
  • 原文地址:https://www.cnblogs.com/David-Lin/p/8342030.html
Copyright © 2020-2023  润新知