Problem Link:

http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

We solve this problem using DP algorithm, which only scans the prices list once. So the algorithm is in O(n) where n is the length of prices list.

By given a list prices[0:n], we represent a trasaction as (b,s) where 0<=b<=s is the day to buy and b<=s<=n-1 is the day to sell.

However, we do not need a O(n) table to store all local optimal solution. Instead, We use only three variables to keep track of local optimal solution.

Suppose prices[0:i] have been scanned, we maitain following variables:

  • l - The day with the lowest prices in prices[0:i]
  • b - The buy day of the local optimal transaction for prices[0:i]
  • s - The sell day of the local optimal transaction for prices[0:i]

We initialize l = b = s = 0, and for each i = 1...n-1, we update by following steps:

  1. If prices[i] < prices[l], then update the lowest price day l.
  2. We update b = l and s = i if one of the following conditions is satisfied.
    1. prices[i] > prices[s]
    2. prices[s] - prices[b] < prices[i] - prices[l]

The following code in python is accepted by oj.leetcode.com.

class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
"""
DP solution: suppose already have following informations in prices[0:i]:
1. Lowest price
2. Current profit presented by the buy price and the sell price
Then for prices[0:i+1], we can update as follows:
If prices[i] > prices[s]:
sell_price = prices[i]
buy_price = lowest_price
elif prices[i]-lowest_price > prices[s] - prices[b]:
buy_price = lowest_price
sell_price = prices[i]
elif prices[i] < lowest_price:
lowest_price = prices[i]
After scan all prices, we return sell_price - buy_price
The initial case:
lowest_price = prices[0]
buy_price = prices[0]
sell_price = prices[0]
And we scan prices from prices[1].
"""
# Special case: prices == []
if not prices:
return 0
# Initialize with prices[0]
b = s = l = 0
# Scan from i = 1 to n-1
for i in xrange(1, len(prices)):
if prices[i] < prices[l]:
l = i
elif prices[i] > prices[s] or prices[s] - prices[b] < prices[i] - prices[l]:
s = i
b = l
return prices[s] - prices[b]

【LeetCode OJ】Best Time to Buy and Sell Stock的更多相关文章

  1. 【LeetCode OJ】Best Time to Buy and Sell Stock III

    Problem Link: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ Linear Time Solut ...

  2. 【LeetCode OJ】Best Time to Buy and Sell Stock II

    Problem Link: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ We solve this prob ...

  3. LeetCode OJ 123. 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 al ...

  4. LeetCode OJ 122. Best Time to Buy and Sell Stock II

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

  5. LeetCode OJ 121. Best Time to Buy and Sell Stock

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

  6. LeetCode OJ:Best Time to Buy and Sell Stock II(股票买入卖出最佳实际II)

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

  7. LeetCode OJ:Best Time to Buy and Sell Stock(股票买卖的最佳时期)

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

  8. 【LeetCode】Best Time to Buy and Sell Stock IV

    Best Time to Buy and Sell Stock IV Say you have an array for which the ith element is the price of a ...

  9. 【leetcode】Best Time to Buy and Sell Stock III

    Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of ...

随机推荐

  1. Linux基础: 挂载镜像文件(Mount & ISO)

    ISO/Ghost 镜像文件概念(裸机安装,无光驱安装,跨平台安装) ISO是镜像文件:所谓镜像文件其实和ZIP压缩包类似,它将特定的一系列文件按照一定的格式制作成单一的文件,以方便用户下载和使用,例 ...

  2. (23)odoo中的domain表达式

    ---------更新日期:09:10 2016-03-03 星期四---------* Domain 表达式             # 用于过滤记录数,相当于sql的where       ('f ...

  3. NSInternalInconsistencyException: loaded the "XXXView" nib but the view outlet was not set

    运行过程中App崩溃,报错如标题. 原因: viewController的view没有绑定xib的view. 解决方法: 在File's Owner中将view与viewController的view ...

  4. 189. Rotate Array -- 将数组前一半移到后一半

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array ...

  5. javascript 数组操作 转

    javascript之数组操作 1.数组的创建 var arrayObj = new Array(); //创建一个数组 var arrayObj = new Array([size]); //创建一 ...

  6. SerialPort使用

    1.简介随 着USB的流行,串口通讯已经应用到日常生活的很多方面了,USB是一种高速的串口通讯协议,USB接口非常复杂,通常被用在需要传输大量数据数据的地 方,如U盘.相机.打印机等.除了USB这种较 ...

  7. iOS开发零碎笔记

    Mac常用操作 全屏截图:同时按住键盘左下方的command和shift   ,然后点击键盘上方的数字键3,便可对整个屏幕截图,截图会自动保存在桌面:任意部分截图:同时按住键盘左下方的ommand和s ...

  8. HDU 4122

    Alice's mooncake shop Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Ot ...

  9. uva 12186

    12186 - Another Crisis Time limit: 3.000 seconds A couple of years ago, a new world wide crisis star ...

  10. linux tar 增量备份命令

    tar --newer-mtime "2013-09-17 00:00:00"   -zcvf /var/www/good.tar.gz    spider/