LeetCode122 Best Time to Buy and Sell Stock II 股票交易最佳时间II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

题源:here;完整实现:here

思路:

三种方案:1 暴力搜索;2 使用中间变量;3 总体思考。

1 暴力搜索

我们将各种能赚钱的组合遍历一遍,时间复杂度高,提交超时。

扫描二维码关注公众号,回复: 2438804 查看本文章
int maxProfit(vector<int>& prices) {
	if (prices.size() < 2) return 0;
	int maxPro = 0;
	int buy = INT_MAX;
	for (int i = 0; i < prices.size(); i++){
		if (buy>prices[i]) buy = prices[i];
		if (prices[i] > buy){
			vector<int> rest(prices.begin() + i, prices.end());
			maxPro = max(maxPro, prices[i] - buy + maxProfit(rest));
		}
	}

	return maxPro;
}

2 中间变量

其实这道题和我们的生活息息相关,可以用一个贪心的策略解决:当股票上涨时持有,下跌时抛出。

int maxProfit2(vector<int>& prices){
	if (prices.size() < 2) return 0;
	int maxPro = 0;
	int buy = INT_MAX, right = 1;
	for (int i = 0; i < prices.size(); i++){
		if (buy>prices[i]) buy = prices[i];
		if (prices[i] > buy && ((i < prices.size() - 1 && prices[i + 1] <= prices[i]) || i == prices.size()-1) ){
			maxPro += prices[i] - buy;
			buy = INT_MAX;
		}
	}

	return maxPro;
}

3 总体思考

当然,如果考虑的再深入一点,就会发现,能赚得最多的方法时可以将所有升值的机会抓住的。

int maxProfit3(vector<int>& prices){
	if (prices.size() < 2) return 0;
	int maxPro = 0;
	for (int i = 1; i < prices.size(); i++){
		if (prices[i]>prices[i - 1])
			maxPro += prices[i] - prices[i - 1];
	}

	return maxPro;
}

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/81210554