LeetCode.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.

股票就是一个大坑,让我去买股票,我是不会去的,这辈子都不可能买股票。如果上帝能像本题这样把所有的价格走势都告诉我了,那肯定要试一试。要想股票收益最大低买高卖就行,所以我们只要遍历数组找到涨价的点就是购买的时机。
低买高卖有两种情况,一种是涨了就卖,一种是一直涨到最高再卖。
第一种情况,找出所有当前比前一天高的价格,然后计算差值和,就是最大收益。

C++代码解法1:

class Solution { 
public: 
    int maxProfit(vector<int>& prices) { 
    	if(prices.empty()  ||  prices.size()  ==  1) 
    		return 0;
    	int maxprofit = 0;
    	for(int i = 1;  i  <  prices.size();  i++){
    		if(prices[i-1] < prices[i]){
    			maxprofit += prices[i] - prices[i-1];
    		}
    	}
    	return maxprofit;
    };  

Python代码解法1:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0 or len(prices) == 1:
            return 0
      	maxprofit = 0 # 总收益
        for i in range(1, len(prices)):
            if prices[i-1] < prices[i]:
                maxprofit += prices[i] - prices[i-1]
        return maxprofit

第二种情况,要麻烦一点,首先要找到买入时机,然后再找到卖出时机。买入时机其实就是当前的价格比第二天低,卖出时机那就是当前价格比第二天高。

C++代码解法2:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty() || prices.size() == 1) 
            return 0;
        int maxprofit = 0;
        int flag = -1;
        for(int i = 0; i < prices.size() - 1; i++){
            if(prices[i] <= prices[i+1]){ // 明天价格要涨或横盘
                if(flag == -1){ // 未持有
                    // 买进
                    flag = prices[i];
                }
                // 如果明天已是最后一天
                if(i == prices.size() - 2){
                    if(flag != -1){ // 已持有
                        // 卖出
                        maxprofit += prices[i+1] - flag;
                        flag = -1;
                    }
                }  
            }else{ // 明天价格要跌
                if(flag != -1){ // 手里持有股票
                    // 赶紧抛
                    maxprofit += prices[i] - flag;
                    flag = -1;
                }
            }
        }
        return maxprofit;
    }
};

Python代码解法2:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0 or len(prices) == 1:
            return 0
        maxprofit = 0 # 总收益
        buyprice = -1 # 持有股票价格
        for i in range(0, len(prices)-1):
            # 先判断是否持有
            if buyprice == -1: # 未持有
                # 判断明天是否涨价,涨价则买入,跌价则继续空账号
                if prices[i] < prices[i+1]:
                    buyprice = prices[i]
            else: # 已持有
                # 判断明天是否跌价,是则抛出
                if prices[i] > prices[i+1]:
                    maxprofit += prices[i] - buyprice
                    buyprice = -1
        
        # 最后还要判断一下最后一天的情况
        if buyprice != -1:
            maxprofit += prices[len(prices)-1] - buyprice
            buyprice = -1
        return maxprofit
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值