给出一个一维数组,分别代表股票每天的价格,121题只能进行一次买卖,122可进行多次买卖,要求计算出最大获利。
121例:只能进行一次买卖,
思路:
将最小的股票价格作为买入价,记录此后的最大获利(卖出价 - 买入价)。
代码1:
int maxProfit(vector<int>& prices) {
int N=prices.size();
int profit=0;
for(int i=N-1;i>0;i--)
{
for(int j=i-1;j>=0;j--)
{
if(prices[i]-prices[j]>profit)//循环遍历,找出最大收益,时间复杂度较大
{
profit=prices[i]-prices[j];
}
}
}
return profit;
}
代码2:
int maxProfit(vector<int>& prices) {
int N=prices.size();
int profit=0;
int buy=0,sell;//初始第一天买入
for(sell=1;sell<N;sell++) //遍历每一天的价格
{
if(prices[sell]-prices[buy]>profit) //若有最大收益,则记录。
{
profit=prices[sell]-prices[buy];
}
else if(prices[sell]<prices[buy]) //若有最低价,则作为买入价
{
buy=sell;
}
}
return profit;
}
122例:可多次买入卖出
思路:
将数据建模为折线图,折现上升代表获利,下降代表亏损,所以每次波谷买入,波峰卖出,确保最大收益。
代码:
int maxProfit(vector<int>& prices) {
int N=prices.size();
int profit=0;
int buy=0,sell;
for(sell=1;sell<N;sell++)
{
if(prices[sell]-prices[buy]>0) //若有收益,则开始买入
{
profit+=prices[sell]-prices[buy]; //有收益就累加
}
//若无收益,则不购买
buy=sell;
}
return profit;
}