题目描述:
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
题解:
原始思路:递归求出当天利润加上剩下天数最大利润【运行错误】
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum=0;
int maxprofit=0;
int minprofit=1e9;
for(int i=0;i<prices.size();i++){
maxprofit=max(maxprofit,prices[i]-minprofit);
minprofit=min(minprofit,prices[i]);
vector<int> price;
price.assign(prices.begin()+i,prices.end());
sum=max(sum,maxprofit+maxProfit(price));
}
return sum;
}
};
正确求解:
方法一: 动态规划
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
int dp[n][2];
dp[0][0]=0;
dp[0][1]=-prices[0];
for(int i=1;i<n;i++){
dp[i][0]=max(dp[i-1][0],dp[i-1][1]+prices[i]);
dp[i][1]=max(dp[i-1][1],dp[i-1][0]-prices[i]);
}
return dp[n-1][0];
}
};
解题思路:每天可以有两种状态:手里没股票和手里有股票。手里没股票分为两种情况:前一天手里也没股票、前一天手里有股票并且今天把股票卖了。手里有股票也分为两种情况:前一天手里有股票、前一天手里没股票并且今天买了股票。最后一天手里一定没股票收入最大。
方法二:贪心算法
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
int sum=0;
for(int i=1;i<n;i++){
if(prices[i]>prices[i-1]){
sum+=prices[i]-prices[i-1];
}
}
return sum;
}
};
解题思路: 将每天的利润最大化,股票交易看作无限次数,所有大于0的日间差额都是利润,利润之和就是最大利润。