LeetCode: Wiggle Subsequence Solution
1/**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}2728// dynamic programming29var wiggleMaxLength = function (nums) {30 const N = nums.length31 const up = Array(N).fill()32 const down = Array(N).fill()33 up[0] = 134 down[0] = 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}
Comments
Loading comments...
Tags
leetcode
greedy
dynamic programming
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Keys And Rooms
Mar 20, 2021