Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

摆动序列-376 #84

Open
sl1673495 opened this issue Jun 17, 2020 · 0 comments
Open

摆动序列-376 #84

sl1673495 opened this issue Jun 17, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。

例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3)  是正负交替出现的。相反, [1,4,7,2,5]  和  [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。

给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。

示例 1:

输入: [1,7,4,9,2,5]
输出: 6
解释: 整个序列均为摆动序列。
示例 2:

输入: [1,17,5,10,13,15,10,5,16,8]
输出: 7
解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。
示例 3:

输入: [1,2,3,4,5,6,7,8,9]
输出: 2
进阶:
你能否用 O(n) 时间复杂度完成此题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/wiggle-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

摆动序列,dp 中对于每一个值的求解都需要记录 lessmore,当前值的最长子序列的最后一个方向是上升,那么就记录为 less,反之记录为 more

在后续的求解中,如果当前的数字大于前面的数字,那么就去找前面的 more 最优解,并且记录在本轮 dp 中的 less 属性上。反之记录在 more 属性上。

最后找出所有 lessmore 中的最大值即可。

  1. 如果是由
/**
 * @param {number[]} nums
 * @return {number}
 */
let wiggleMaxLength = function (nums) {
  let dp = []
  let n = nums.length
  if (!n) {
    return 0
  }

  dp[0] = {
    less: 1,
    more: 1,
  }

  let res = 1

  for (let i = 1; i < n; i++) {
    let num = nums[i]
    dp[i] = {
      less: 1,
      more: 1,
    }
    for (let j = 0; j < i; j++) {
      let prevNum = nums[j]
      let max = 1
      if (num > prevNum) {
        dp[i].less = Math.max(dp[i].less, dp[j].more + 1)
      } else if (num < prevNum) {
        dp[i].more = Math.max(dp[i].more, dp[j].less + 1)
      }
    }
    res = Math.max(res, dp[i].more, dp[i].less)
  }
  return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant