zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    3月18
    线段树求后继+环——cf1237D
    排序+stl——cf1237C
    思维+双指针+环——cf1244F
    模拟+双指针——cf1244E
    树的性质——cf1244D
    数学思维——cf1244C
    树的直径变形——cf1238F
    ac自动机暴力跳fail匹配——hdu5880
    状态压缩dp增量统计贡献——cf1238E(好题)
  • 原文地址:https://www.cnblogs.com/slurm/p/5345977.html
Copyright © 2011-2022 走看看