题目:买卖股票的最佳时机 II
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
解题思路:找到第一个可以购买的股票,然后找到这支股票的递增最大出售点,在这个点出售,计算利润。然后在下个点继续购买,迭代进行,代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int PrSzie = prices.size();
if(PrSzie == 1)
{
return 0;
}
//找到第一个买入位置
int pos = 0;
for(int i = 0; i < PrSzie - 1;++i)
{
if(prices[i] < prices[i+1])
{
pos = i;
break;
}
}
int profit = 0;
for(int i = pos;i < PrSzie - 1 ;++i)
{
if(prices[i] > prices[i+1])
{
profit += prices[i] - prices[pos];
pos = i+1;
}
if(i + 1 == PrSzie - 1)
{
profit += prices[i+1] - prices[pos];
}
}
return profit;
}
};
注意:这里使用了i+1的下标,小心数组越界问题