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

    思路

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    代码:oj测试代码 Runtime: 111 ms

     1 class Solution:
     2     # @param prices, a list of integer
     3     # @return an integer
     4     def maxProfit(self, prices):
     5         # none case or one element case
     6         if prices is None or len(prices)<2 :
     7             return 0
     8         # dp
     9         min_buy = 0
    10         max_profit = 0
    11         for i in range(1,len(prices)):
    12             if prices[i]<prices[min_buy]:
    13                 min_buy = i
    14             max_profit = max(prices[i]-prices[min_buy],max_profit)
    15         return max_profit

    思路

    典型的动态规划题目。

    跟求最小子集的和这道题(http://www.cnblogs.com/xbf9xbf/p/4240510.html)类似。

    个人认为这类题目的精髓在于“在每一步,我们维护两个变量,一个是全局最优,就是到当前元素为止最优的解是,一个是局部最优,就是必须包含当前元素的最优的解”。

    对于这道题来说,有一个小梗需要想明白:如果prices[i]就是到i为止最小的值,那么prices[i]-prices[min_buy]不是等于0了么?

    请注意,回顾动态规划的规则:一定要包含当前元素的最优解。既然当前元素已经是历史最小值了,那么还非要包含当前元素的最优解,不正是他自身减去自身么?

    维护一个max_profit(最大利润),一个min_buy(历史最低点)。

    1. 如果当前的prices[i]小于prices[min_buy],则更新min_buy。

    2. 取prices[i]-prices[min_buy]和max_profit中较大的一个,作为max_profit的值。

    最后返回max_profit即可。

  • 相关阅读:
    pymysql 查询大量数据导致内存使用过高优化方案
    docker-compose文件
    Flask关于request一些方法和属性的整理
    gitignore 文件中忽略项不起作用的解决方法
    Django 时区
    django-apscheduler定时任务
    结队-贪吃蛇游戏-项目进度
    团队-科学计算器-开发环境搭建过程
    《团队-科学计算器-设计文档》
    《结对-贪吃蛇-设计文档》
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4264748.html
Copyright © 2011-2022 走看看