# LeetCode: Wiggle Subsequence Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[]} nums3 * @return {number}4 */5// greedy6var wiggleMaxLength = function (nums) {7  const N = nums.length8  let res = 19  let pos = {10    peak: false,11    valley: false,12  }13  for (let i = 1; i < N; i++) {14    if (nums[i] > nums[i - 1] && !pos.peak) {15      pos.valley = false16      pos.peak = true17      res += 118    }19    if (nums[i] < nums[i - 1] && !pos.valley) {20      pos.valley = true21      pos.peak = false22      res += 123    }24  }25  return res26}27
28// dynamic programming29var wiggleMaxLength = function (nums) {30  const N = nums.length31  const up = Array(N).fill()32  const down = Array(N).fill()33  up = 134  down = 135  for (let i = 1; i < N; i++) {36    if (nums[i] > nums[i - 1]) {37      up[i] = down[i - 1] + 138      down[i] = down[i - 1]39    } else if (nums[i] < nums[i - 1]) {40      up[i] = up[i - 1]41      down[i] = up[i - 1] + 142    } else {43      up[i] = up[i - 1]44      down[i] = down[i - 1]45    }46  }47  return Math.max(up[N - 1], down[N - 1])48}```

## Tags

leetcode

greedy

dynamic programming

## Next Post

LeetCode: Keys And Rooms

Mar 20, 2021

Search Posts