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
    
  • 相关阅读:
    mybatis(八)手写简易版mybatis
    mybaits(七)spring整合mybaits
    Java学习之String StringBuffer StringBuilder区别
    Java学习之基本概念
    java多态
    HashMap变成线程安全方法
    java高级开发工程师面试题
    同步和异步
    Oracle创建索引的原则(转)
    导入maven工程错误
  • 原文地址:https://www.cnblogs.com/slurm/p/5345977.html
Copyright © 2011-2022 走看看