LeetCode:best time to buy and sell stock

best time to buy and sell stock -i

题目:
Say you have an array for which the i th element is the price of a given stock on day i.

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.
思路:
思路一:抓住一点,无论买还是卖 ,都要“赚”最多 ,所谓赚最多,就是花的少,卖的多
思路二:剑指offer【股票的最大利润】。其实两种思想的本质一样。
代码:

/*思路一代码,思路一的思想更为通用,试用于-iii的解决*/
class Solution {
public:
	int maxProfit(vector<int> &prices) {
		if (prices.size() < 2)
			return 0;
		int buy1 = INT_MIN;
		int sell_one = 0;
	
		for (int i = 0; i < prices.size(); i++){//计算每次操作后赚钱最多
			buy1 = max(-prices[i], buy1);//第一次买后  因为是花钱,所以赚了 -prices[i]元  
			sell_one = max(sell_one, buy1 + prices[i]);//第一次卖后  赚的钱
		
		}
		return sell_one;
	}
};

best time to buy and sell stock -ii

题目:
Say you have an array for which the i th 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 (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).
思路:
判断相邻是否递增,因为连续递增可以合起来看为一次买入卖出操作,所以统计所有递增量即可.

[7, 1, 5, 6] 第二天买入,第四天卖出,收益最大(6-1),所以一般人可能会想,怎么判断不是第三天就卖出了呢? 这里就把问题复杂化了,根据题目的意思,当天卖出以后,当天还可以买入,所以其实可以第三天卖出,第三天买入,第四天又卖出((5-1)+ (6-5) === 6 - 1)。所以算法可以直接简化为只要今天比昨天大,就卖出。
代码:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length<2)
            return 0;
        int res = 0;
        for(int i =1;i<prices.length;i++){
            if(prices[i]>prices[i-1])
                res += prices[i]-prices[i-1];
        }
        return res;
    }
}

best time to buy and sell stock -iii

题目:
Say you have an array for which the i th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:
抓住一点,无论买还是卖 ,都要“赚”最多 ,所谓赚最多,就是花的少,卖的多
代码:

/*
*抓住一点,无论买还是卖 ,都要“赚”最多   ,所谓赚最多,就是花的少,卖的多
*/
class Solution {
public:
	int maxProfit(vector<int> &prices) {
		if (prices.size() < 2)
			return 0;
		int buy1 = INT_MIN;
		int sell_one = 0;
		int buy2 = INT_MIN;
		int sell_two = 0;
		for (int i = 0; i < prices.size(); i++){//计算每次操作后赚钱最多
			buy1 = max(-prices[i], buy1);//第一次买后  因为是花钱,所以赚了 -prices[i]元  
			sell_one = max(sell_one, buy1 + prices[i]);//第一次卖后  赚的钱
			buy2 = max(buy2, sell_one - prices[i]);//第二次买 ,买后赚的钱数为 第一次赚的 - 第二次买花的
			sell_two = max(sell_two, buy2 + prices[i]);// 同第一次卖   
		}
		return sell_two;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值