• leetcode @python 123. Best Time to Buy and Sell Stock III


    题目链接

    https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

    题目原文

    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 at most two transactions.

    题目大意

    给定不同交易日的股票价格,只能做两次交易,求最大的收益

    解题思路

    First assume that we have no money, so buy1 means that we have to borrow money from others, we want to borrow less so that we have to make our balance as max as we can(because this is negative).

    sell1 means we decide to sell the stock, after selling it we have price[i] money and we have to give back the money we owed, so we have price[i] - |buy1| = prices[i ] + buy1, we want to make this max.

    buy2 means we want to buy another stock, we already have sell1 money, so after buying stock2 we have buy2 = sell1 - price[i] money left, we want more money left, so we make it max

    sell2 means we want to sell stock2, we can have price[i] money after selling it, and we have buy2 money left before, so sell2 = buy2 + prices[i], we make this max.

    So sell2 is the most money we can have.

    代码

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            s1, s2 = 0, 0
            b1, b2 = -2147483648, -2147483648
            for i in range(len(prices)):
                b1 = max(b1, -prices[i])
                s1 = max(s1, b1 + prices[i])
                b2 = max(b2, s1 - prices[i])
                s2 = max(s2, b2 + prices[i])
            return s2
    
  • 相关阅读:
    java 单例模式-饿懒汉模式
    Java注解
    Java集合
    Java数据类型
    java实现多线程三种方法
    Java并发 线程池
    spring ioc(反转控制)
    事件驱动的Java框架
    js 标签属性与导航
    input 标签和a标签实现超链接的区别
  • 原文地址:https://www.cnblogs.com/slurm/p/5345977.html
Copyright © 2020-2023  润新知