LeetCode122:购买股票的最佳时机II

解析:

        该题和121不一样之处就是可以买卖多次,但是难度没有增加多少,基本的思路就是,低买高卖。如果i天的价格低于i+1天的价格且此时手里没有股票,则可以买进;如果第i天价格高于第i+1天,且手里有股票,则可以卖出;如果第i天低于第i+1天,但是第i+1天是最后一天,则最后以一天卖出。把所有的差值计算出来,就是最大的利润。

代码:

int maxProfit(vector<int>& prices) 
{
	int maxProfit = 0;//最大利润
	if (prices.empty())
		return maxProfit;
	int days = prices.size();
	bool buy = false;//手里是否有股票的标记
	int i;
	int buyPrice;
	for (i = 0; i < days - 1; i++)
	{		
		if (prices[i + 1] > prices[i] && !buy)
		{
			buyPrice = prices[i];
			buy = true;
		}
		else if ((prices[i + 1] < prices[i] ) && buy)
		{
			maxProfit += prices[i] - buyPrice;
			buy = false;
		}
	}
	if (i == days - 1 && buy)//最后一天,且手里有股票
	{
		maxProfit += prices[i] - buyPrice;
		buy = false;
	}
	return maxProfit;
}

leetCode上有一种比较简单的做法,就是用一个数组保存,第i+1的值和第i个值的差,然后计算数组中所有正数的和,即为最终的结果。

    int maxProfit(vector<int>& prices) {
	if (prices.empty()) return 0;
	vector<int> benefit;
	int result = 0;
	for (auto it = prices.begin(); it != prices.end()-1; it++) {
		benefit.push_back(*(it + 1) - *it);
	}
	for (auto a : benefit) {
		if (a > 0) result += a;
	}
	return result;
    }

猜你喜欢

转载自blog.csdn.net/qq_36214481/article/details/84927864