动态规划,dp[i]=max(dp[i-1],dp[k]+prices[i]-nums[k+1]),k+1>=0&&k+1<=i-1;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
if(n==0)
return 0;
int i;
int B=-prices[0];
int dp[n];
dp[0]=0;
for(i=1;i<n;i++)
{
B=max(B,dp[i-1]-prices[i]);
dp[i]=max(dp[i-1],B+prices[i]);
}
return dp[n-1];
}
};
可以用贪心法;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit=0;
int n=prices.size();
for(int i=1;i<n;i++)
{
int dif=prices[i]-prices[i-1];
if(dif>0)
profit+=dif;
}
return profit;
}
};