It taked me a long time to understand the solutions in Discussion, so I decided to explain it by myself.
Solution
It’s easy to reach a O(n^2) solution. However, the follow up asks us to solve this problem in linear time. We can’t define upper[i], down[i] as the longest wiggle subsequence ends at i and is upper/lower case. When you define the state in this way, you can’t avoid to traverse back and make the time complexity O(n^2). One solution is to define upper[i], down[i] as the longest wiggle subsequence before i. This state prevent us from traversing again. But we can’t always define dp in this way because this needs the transistion equation only use the i-1 state to update state i. Why this defination works? See the following proof:
Code
1 | class Solution { |