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. C# BackgroundWorker的使用 转

    转自http://www.cnblogs.com/tom-tong/archive/2012/02/22/2363965.html  感谢作者详细的介绍 C# BackgroundWorker的使用 ...

  2. 图片填充UIImageView大小不对

    http://www.2cto.com/kf/201507/412894.html UIView的contentMode属性: 默认为Scale To Fill,会保留view的比例,不会完全按照设定 ...

  3. 436. Find Right Interval ——本质:查找题目,因此二分!

    Given a set of intervals, for each of the interval i, check if there exists an interval j whose star ...

  4. MVC1-5直接访问静态页面

    MVC模式下默认是无法访问站点内静态页面,昨日百度找了半天试了半天才试成功. 默认在Views文件外的静态页面可以访问,若要访问Views里的静态页面则需要修改View文件夹中的web.config: ...

  5. mac 找文件

    如何找到 etc 方法1: ! D# D! s2 F" f 七度苹果电脑软件1.打开Finder,按快键盘 Command + Shift + G,即可调出 前往文件夹 ,也可以左上角 找到 ...

  6. C#入门篇6-8:字符串操作 深入研究字符串的内存驻留机制

    //字符串的内存驻留机制 public static void Test() { //当有多个字符串变量包含了同样的字符串实际值时, //CLR可能不会为它们重复地分配内存,而是让它们统统指向同一个字 ...

  7. spring mvc读取url变量

    @RequestMapping(value="/{id}/{name}", method=RequestMethod.GET) public ModelAndView getUrl ...

  8. 转载——PLSQL developer 连接不上64位Oracle 解决办法

    前两天刚下载了oracle 11g 64位的最新版本,安装成功之后,再安装PLSQL.结果使用PLSQL访问数据库时,死活连接不上.报错如下: Could not load "……\bin\ ...

  9. NDK JNI 的关键点

    1.System.loadLibrary 的名字是在Android.mk里面设定的   LOCAL_MODULE    := httpdown,MODULE   后面跟的就是了 2.如何正确调用到关键 ...

  10. 第46套题【STL】【贪心】【递推】【BFS 图】

    已经有四套题没有写博客了.今天改的比较快,就有时间写.今天这套题是用的图片的形式,传上来不好看,就自己描述吧. 第一题:单词分类 题目大意:有n个单词(n<=10000),如果两个单词中每个字母 ...