【LeetCode OJ】Best Time to Buy and Sell Stock
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:
- If prices[i] < prices[l], then update the lowest price day l.
- We update b = l and s = i if one of the following conditions is satisfied.
- prices[i] > prices[s]
- 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的更多相关文章
- 【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 ...
- 【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 ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- 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 ...
- 【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 ...
- 【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 ...
随机推荐
- Qt之QSizePolicy
简述 QSizePolicy类是一个描述布局水平和垂直方向调整策略的属性. 大小策略会影响布局引擎处理部件的方式,部件加入布局以后,会返回一个QSizePolicy,描述了其水平和垂直方向的大小策略. ...
- hibernate annotation注解方式来处理映射关系
在hibernate中,通常配置对象关系映射关系有两种,一种是基于xml的方式,另一种是基于annotation的注解方式,熟话说,萝卜青菜,可有所爱,每个人都有自己喜欢的配置方式,我在试了这两种方式 ...
- HDUoj-------(1128)Self Numbers
Self Numbers Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)To ...
- Binary Tree Level Order Traversal II [LeetCode]
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...
- Spring Data Jpa配置
Spring Data JPA提供的接口,也是Spring Data JPA的核心概念: 1:Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组 ...
- spring使用jackson返回object报错:Handler execution resulted in exception: Could not find acceptable representation
问题:在springmvc中添加Jackson jar包返回Object类型,处理器方法的produces属性不写,默认根据类型,但如果指定了(错误原因)produces = "text/h ...
- WebDataTree 使用XML做数据源绑定数据
英文版原文链接:http://www.infragistics.com/help/topic/e5f07b51-ee2d-4a33-aaac-2f43cffff327 所使用的控件版本为:Infrag ...
- mvc+ef+oracle环境中报错:ORA-00001: 违反唯一约束条件
分析原因: 在oracle中,主健不能自动生成,不过可以通过“序列”来实现,如果是这样的话,问题很可能就出在“序列”上了: ORACLE表主键ID突然从已经存在的ID值开始自动生成,导致违反主键唯一性 ...
- mysql把查询的结果格式成日期
SELECT *,FROM_UNIXTIME(addtime, '%Y-%m-%d %H:%i:%S') as riqi FROM `test`
- C#入门篇6-6:字符串操作 StringBiulder string char[]之间的转化
//StringBiulder string char[]之间的转化 public static void Fun3() { StringBuilder sb = new StringBuilder( ...