Another interesting DP. Lesson learnt: how you define state is crucial..
1. if DP[i] is defined as, longest wiggle(up\down) subseq AT number i, you will have O(n^2) solution
class Solution
{
struct Rec
{
Rec(): mlen_dw(), mlen_up(){}
Rec(int ldw, int lup): mlen_dw(ldw), mlen_up(lup){}
int mlen_dw;
int mlen_up;
};
public:
int wiggleMaxLength(vector<int>& nums)
{
int n = nums.size();
if(n < ) return n; vector<Rec> dp(n);
dp[].mlen_up = dp[].mlen_dw = ; int ret = ;
for(int i = ; i < n; i ++)
{
int cv = nums[i];
for(int j = i - ; j >= max(, ret - ); j --)
{
if(cv > nums[j])
{
dp[i].mlen_up = max(dp[i].mlen_up, dp[j].mlen_dw + );
}
else if(cv < nums[j])
{
dp[i].mlen_dw = max(dp[i].mlen_dw, dp[j].mlen_up + );
}
ret = max(ret, max(dp[i].mlen_dw, dp[i].mlen_up));
}
} return ret;
}
};
2. if DP[i] is defined as, longest wiggle(up\down) subseq SO FAR UNTIL number i, you will have O(n) solution
class Solution
{
struct Rec
{
Rec(): mlen_dw(), mlen_up(){}
Rec(int ldw, int lup): mlen_dw(ldw), mlen_up(lup){}
int mlen_dw;
int mlen_up;
};
public:
int wiggleMaxLength(vector<int>& nums)
{
int n = nums.size();
if(n < ) return n; vector<Rec> dp(n);
dp[].mlen_up = dp[].mlen_dw = ; int ret = ;
for(int i = ; i < n; i ++)
{
int cv = nums[i];
dp[i] = dp[i - ];
if(cv > nums[i - ])
{
dp[i].mlen_up = max(dp[i].mlen_up, dp[i - ].mlen_dw + );
}
else if(cv < nums[i - ])
{
dp[i].mlen_dw = max(dp[i].mlen_dw, dp[i - ].mlen_up + );
}
ret = max(ret, max(dp[i].mlen_dw, dp[i].mlen_up));
} return ret;
}
};
3. And, there's always smarter solution - GREEDY!
https://discuss.leetcode.com/topic/52074/concise-10-lines-code-0ms-acepted