leetcode#121#122#123 Best Time to Buy and Sell Stock

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

#121 只买入卖出各一次,选取到今天为止最小值为买入价,比较今后的卖出价格的收益和之前记录的收益。

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Input: [7, 1, 5, 3, 6, 4]
Output: 5

int maxProfit121(vector<int>& prices) {
		int n = prices.size();
		if (n <= 1) 
			return 0;
		int minPrice = prices[0];
		int profit = 0;
		for (int i = 1; i < n; i++){
			minPrice = min(minPrice, prices[i]);
			if (profit < prices[i] - minPrice)
				profit = prices[i] - minPrice;
		}
		return profit;
	}

#122 买入前必须卖出已有股票,不可以连续买入两天,每次交易表示为前一天价格买入,当前价格卖出。

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Input: [7,1, 5, 3, 6, 4]
Output:(5-1) + (6-3) = 7

int maxProfit122(vector<int>& prices) {
		int n = prices.size();
		if (n <= 1)
			return 0;
		int profit = 0;
		for (int i = 1; i < n; i++){
			if (prices[i] > prices[i - 1])
				profit += prices[i] - prices[i - 1]; //前一天价格买入,当天卖出。不可以连续买入。
		}
		return profit;
	}


#123 交易次数最多为两次,分别用两个vector动态记录从[0,i], [i, n-1]的最大收益

Design an algorithm to find the maximum profit. You may complete at most two transactions.You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Input: [7,1, 5, 3, 6, 4]
Output: 7
int maxProfit123(vector<int>& prices) {
		int n = prices.size();
		if (n <= 1)
			return 0;
		int profit = 0;
		vector<int> p1(n); //记录[0,i]内买卖最大收入
		vector<int> p2(n); //记录[i,n-1]内买卖最大收入
		
		int buyPrice = prices[0]; //从前往后遍历,当前值为买入价
		int sellPrice = prices[n - 1]; //从后往前遍历,当前值为卖出价

		for (int i = 1; i < n; i++){
			buyPrice = min(buyPrice, prices[i]);
			p1[i] = max(p1[i - 1], prices[i] - buyPrice);
		}
		for (int i = n - 2; i >= 0; i--){
			sellPrice = max(sellPrice, prices[i]);
			p2[i] = max(p2[i + 1], sellPrice - prices[i]);
		}
		for (int i = 0; i < n; i++)
			profit = max(profit, p1[i] + p2[i]);
		return profit;
	}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值