• 边工作边刷题:70天一遍leetcode: day 14


    Best Time to Buy and Sell Stock III/IV

    IV是k的解,可以特殊化到2的。有趣的问题是III的左右两遍扫描解法和IV的关联性。其实在从左向右扫描的时候就是更新global[i][1],从右向左扫描是更新global[i][2](基于global[i][1])。为什么IV中要maintain local而III没有还没有理解透,现在的想法是实际上每次计算global的时候已经包含了local的计算,因为local的主要目的是从k-1次交易构建第k次交易。

    还有一个细节就是在当天是可以同时买卖的,这样在计算2次交易profit的时候(III),是左右同一天的profit加和。而IV,local也是用的前一天的卖的情况(所以前一天可以再买回来今天再卖)

    class Solution(object):
        def maxProfit(self, prices):
            """
            :type prices: List[int]
            :rtype: int
            """
            maxProfit = 0
            n = len(prices)
            if n<2: return 0
    
            profits = [0]*n
            minPrice = prices[0]
            for i in range(1, n):
                maxProfit = max(maxProfit, prices[i] - minPrice)
                profits[i]=maxProfit
                minPrice = min(minPrice, prices[i])
            print maxProfit
            maxPrice = prices[n-1]
            maxProfit = 0
            for i in range(n-2, -1, -1):
                maxProfit = max(maxProfit, maxPrice - prices[i]+profits[i])
                maxPrice = max(maxPrice, prices[i])
                
            return maxProfit
    
  • 相关阅读:
    QSslError 类
    QNetworkRequest 请求类
    QFTP走了以后QNetworkAccessManager出现了
    Android之SQLite总结
    Android之Handler机制
    Android之SeekBar总结(一)
    Android之测试相关知识点
    Android数据储存之SharedPreferences总结
    android studio的常用快捷键
    BitmapFactory.Options详解
  • 原文地址:https://www.cnblogs.com/absolute/p/5677829.html
Copyright © 2020-2023  润新知