LeetCode 买卖股票的最佳时机II
程序员文章站
2022-07-08 08:58:33
...
LeetCode 买卖股票的最佳时机II
题目
示例
思路
买入的时候从最前面开始寻找最小的元素,以最低价格买入,卖出的时候必须在持有股票,并且寻找后面的极大的元素,然后在这个时候卖出。
代码
int maxProfit(int* prices, int pricesSize)
{
int buy = 0 , sell = 0, sum=0, i=0;
while (i < pricesSize)
{
if (buy == 0)
{
if (i+1 < pricesSize && prices[i] < prices[i+1])
{
buy = prices[i];
sell = prices[i+1];
}
}
else
{
if (i+1 >= pricesSize ||prices[i] > prices[i+1])
{
sum += sell-buy;
buy = 0;
}
else
sell = prices[i+1];
}
i++;
}
return sum;
}
这里股票的价格是有可能取0的,因此在代码中这条语句是会漏掉交易的**if (buy == 0)
**,但股票价格是不会为负的,因此在没有持有股票的时候,对 buy 赋值为-1。
改善
int maxProfit(int* prices, int pricesSize)
{
int buy = -1 , sell = 0, sum=0, i=0;
while (i < pricesSize)
{
if (buy == -1)
{
if (i+1 < pricesSize && prices[i] < prices[i+1])
{
buy = prices[i];
sell = prices[i+1];
}
}
else
{
if (i+1 >= pricesSize ||prices[i] > prices[i+1])
{
sum += sell-buy;
buy = -1;
}
else
sell = prices[i+1];
}
i++;
}
return sum;
}