使用动态规划,下面的代码可以通过210个测试,最后1个(第211个)会超时。说明思路是正确的,但是其中有一些是无效的计算。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
if(n==)
{
return ;
}
int N=;
int **D;
D = new int*[N];
for(int i=;i<n;i++){
D[i]=new int[N];
}
for(int i=;i<n;i++){
for(int j=i;j<n;j++){
int pj=prices[j];
int pi=prices[i];
D[i][j]=pj-pi;
}
} for(int len=;len<n;len++){
for(int i=;i<n-;i++){
int j=i+len;
if(j>=n){
break;
}
int m_ij=D[i][j];
int max_k=;
for(int k=i+;k<j;k++){
int m11 = D[i][k];
int m12=;
if(k+<j){
m12=D[k+][j];
}
int m1=m11+m12; int m21=D[k][j];
int m22=;
if(k->i){
m22=D[i][k-];
}
int m2=m21+m22;
int m=max(m1,m2);
max_k=max(max_k,m);
}
D[i][j]=max(m_ij,max_k);
}
} return D[][n-];
}
};
再提供网上AC的参考实现:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= )
return ;
int s0 = ;
int s1 = -prices[];
int s2 = INT_MIN;
for (int i = ; i < prices.size(); i++){
int pre0 = s0;
int pre1 = s1;
int pre2 = s2;
s0 = max(pre0, pre2);
s1 = max(pre0 - prices[i], pre1);
s2 = pre1 + prices[i];
} return max(s0, s2);
}
};
再补充一个:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == || len == )
return ;
if(len == )
return prices[] > prices[] ? prices[] - prices[] : ; vector<int> s0(len);
vector<int> s1(len);
vector<int> s2(len);
s0[] = ;
s1[] = max(-prices[], -prices[]);
s2[] = prices[] - prices[];
for(int i = ; i < len; i++)
{
s0[i] = max(s0[i-], s2[i-]);
s1[i] = max(s0[i-] - prices[i-], s1[i-]);
s2[i] = s1[i-] + prices[i - ];
}
return max(max(s0[len-], s2[len-]), s1[len-] + prices[len-]);
}
};