zoukankan      html  css  js  c++  java
  • leetcode 【 Best Time to Buy and Sell Stock III 】python 实现

    题目

    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.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    代码:Runtime: 175 ms

     1 class Solution:
     2     # @param prices, a list of integer
     3     # @return an integer
     4     def maxProfit_with_k_transactions(self, prices, k):
     5         days = len(prices)
     6         local_max = [[0 for i in range(k+1)] for i in range(days)]
     7         global_max = [[0 for i in range(k+1)] for i in range(days)]
     8         for i in range(1,days):
     9             diff = prices[i] - prices[i-1]
    10             for j in range(1,k+1):
    11                 local_max[i][j] = max(local_max[i-1][j]+diff, global_max[i-1][j-1]+max(diff,0))
    12                 global_max[i][j] = max(local_max[i][j], global_max[i-1][j])
    13         return global_max[days-1][k]
    14 
    15     def maxProfit(self, prices):
    16         if prices is None or len(prices)<2:
    17             return 0
    18         return self.maxProfit_with_k_transactions(prices, 2)

    思路

    不是自己想的,参考这篇博客http://blog.csdn.net/fightforyourdream/article/details/14503469

    跟上面博客一样的思路就不重复了,下面是自己的心得体会:

    1. 这类题目,终极思路一定是往动态规划上靠,我自己概括为“全局最优 = 当前元素之前的所有元素里面的最优 or 包含当前元素的最优

    2. 这道题的动归的难点在于,只靠一个迭代公式无法完成寻优。

    思路如下:

    global_max[i][j] = max( global_max[i-1][j], local_max[i][j])

    上述的迭代公式思路很清楚:“到第i个元素的全局最优 = 不包含第i个元素的全局最优 or 包含当前元素的局部最优

    但问题来了,local_max[i][j]是啥?没法算啊~

    那么,为什么不可以对local_max[i][j]再来一个动态规划求解呢?

    于是,有了如下的迭代公式:

    local_max[i][j] = max(local_max[i-1][j]+diff, global_max[i-1][j-1]+max(diff,0))

    上面的递推公式 把local_max当成寻优目标了,思路还是fellow经典动态规划思路。

    但是,有一部分我一开始一直没想通(蓝字部分),按照经典动态规划思路直观来分析,就应该是local_max[i-1][j]啊,怎么还多出来一个diff呢?

    ===========================================================================================================

    时隔几天再想想,求解local_max[i][j]的过程其实并不能算传统动态规划的思路,之前的思路有些偏差。原因是local_max本身就不是一个“全局”最优,因为计算local[i][j]的时候就已经把最近的一个元素算进去了。local_max[i][j] = max(local_max[i-1][j]+diff, global_max[i-1][j-1]+max(diff,0))这个公式的得来,也真心是原作者巧妙分析的结果,一下就解决了求解N次交易最优的问题。只能膜拜并记住这部分代码。

  • 相关阅读:
    tuple 元组及字典dict
    day 49 css属性补充浮动 属性定位 抽屉作业
    day48 选择器(基本、层级 、属性) css属性
    day47 列表 表单 css初识
    day 46 http和html
    day 45索引
    day 44 练习题讲解 多表查询
    day 40 多表查询 子查询
    day39 表之间的关联关系、 补充 表操作总结 where 、group by、
    day38 数据类型 约束条件
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4307840.html
Copyright © 2011-2022 走看看