[Leetcode] #121#122#123#188 Best Time to Buy and Sell Stock I & II & III & IV

给出每天的价格,求最大利润。

I 一次买进卖出

int maxProfit(vector<int>& prices) {
	int profit = 0, max_profit = 0;
	for (int i = 1; i < prices.size(); i++){
		int diff = prices[i] - prices[i - 1];
		if (profit >= 0)
			profit += diff;
		else
			profit = diff;
		if (profit > max_profit)
			max_profit = profit;
	}
	return max_profit;
}

II 无限次买进卖出

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

III  最多两次买进卖出

int maxProfit(vector<int>& prices) {
	int n = prices.size();
	int global[3] = { 0 }, local[3] = { 0 };
	for (int i = 1; i<n; i++){
		for (int j = 2; j >= 1; j--){
			int diff = prices[i] - prices[i - 1];
			local[j] = max(global[j - 1] + max(diff, 0), local[j] + diff);
			global[j] = max(global[j], local[j]);
		}
	}
	return global[2];
}

IV 最多K次买进卖出

int maxProfit(int k, vector<int>& prices) {
	int n = prices.size();
	if (k >= n - 1) return maxProfitlarge(prices);
	int global[k + 1] = { 0 }, local[k + 1] = { 0 };
	for (int i = 1; i<n; i++){
		for (int j = k; j >= 1; j--){
			int diff = prices[i] - prices[i - 1];
			local[j] = max(global[j - 1] + max(diff, 0), local[j] + diff);
			global[j] = max(global[j], local[j]);
		}
	}
	return global[k];
}

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

GitHub-Leetcode:https://github.com/wenwu313/LeetCode

解题思路四:http://www.cnblogs.com/grandyang/p/4295761.html

解题思路三: http://www.cnblogs.com/grandyang/p/4281975.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值