【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 Solution
We try to solve this problem in O(n) time in the help of the algorithm in Best Time to Buy and Sell Stock, which can return the max profit by given a list of prices.
As transaction definition in Best Time to Buy and Sell Stock, we modify the algorithm that returns the best transaction (b, s) by given price list prices[0:n] where
- prices[i] <= prices[s0], for i = b0, ..., n-1
- prices[i] >= prices[b0], for i = 0, ..., s0
By the help of method find_best_transaction, the following algorithm will solve the problem in O(n) time:
1. By given the price list prices[0..n01], find the best transaction (b,s) = find_best_transaction(prices)
2. Find the maximum profit for the following three parts divided by b and s:
P1: the maximum profit for the price list price[0..b-1]
P2: the maximum profit for the price list price[b+1..s-1].inverse()
P3: the maximum profit for the price list price[s+1..n-1]
3. Return prices[s]-prices[b] + max(P1,P2,P3)
Correctness
Now we woul prove the algorithm above is correct. Sicne we are asked to find at most two transactions, there are two cases: 1) (b0, s0) is one of the two transactions; 2) (b0, s0) is not in the result. For case 1) we can solve the problem by find the max profit for prices[0:b0] and prices[s0:n], and choose the bigger one as the second transaction.
Now we consider the case 2), let (b1, s1) and (b2, s2) be the two transactions where 0 <= b1 < s1 < b2 < s2 <= n-1. Also, we can have the following corolarries:
- b0 <= s1 <= s0, we prove it by contradiction:
- if s1 < b0 (-----s1--b0-----s0------), then (b2,s2) could be replaced by (b0, s0).
- if s1 > s0 (----b0----s0--s1--------), then (b1, s1) could be replaced by (b0, s0).
- b0 <= b2 <= s0, we prove it by contradiction:
- if b2 < b0 (---b2----b0-------s0---), then (b2, s2) could be replaced by (b0, s0).
- if b2 > s0 (---------b0----s0--b2--), then (b1, s1) could be replaced by (b0, s0).
- For b1 < s1, since s1 <= s0, then s1 could be b0, since prices[b0] <= prices[i] for i = 0,...,s0.
- For s2 > b2, since b2 >= b0, then s2 could be s0, since prices[s0] <= prices[i] for i = b0, ..., n-1
Therefore, we can find the best s1 and b2 scanning between b1(b0) and s2(s0), which only takes O(n) time and is a little tricky.
Suppose the optimal trasactions can be as follows:
-----b1(b0)----s1------b2------s2(s0)----
The profit should be (p[s1] - p[b1]) + (p[s2]-p[b2]) which can be rewritten as (p[s2]-p[b1]) + (p[s1]-p[b2]). Therefore, it equals to finding best transaction (b2, s1) where the given prices list is the inverse of prices[b1+1, ..., s2-1].
From the two cases above, our algorithm will give the correct answer.
Python Code
The following is the python implementation accepted by oj.leetcode.com.
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
n = len(prices)
if n < 2:
return 0
# Find the single best transaction
b0, s0, profit0 = self.find_best_transaction(prices) # Calculate the max profit of the three parts partitioned by (b0, s0)
profit1 = profit2 = profit3 = 0
if b0 > 0:
profit1 = self.find_best_transaction(prices[:b0])[2]
if s0 > b0 + 1:
profit2 = self.find_best_transaction(prices[b0+1:s0][::-1])[2]
if s0 < n-1:
profit3 = self.find_best_transaction(prices[s0+1:])[2] # Return the best case
return profit0 + max(profit1, profit2, profit3) def find_best_transaction(self, prices):
"""
Return the transaction (b,s) that obtains maximum profit.
@param prices: a list of prices
@return: (b,s) where 0 <= b < s < len(prices)
"""
# 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 b, s, prices[s]-prices[b]
【LeetCode OJ】Best Time to Buy and Sell Stock III的更多相关文章
- 【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】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 ...
- 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】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 ...
- LeetCode 笔记23 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 ...
- 【leetcode刷题笔记】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 ...
随机推荐
- Compound Interest Calculator3.0续
1.你写的程序能让客户随意操作吗?误输入数据.不小心做了非常规的操作程序是什么反应? 2.如果向银行贷款10万元,年利率6.5%,期限为10年,那么每月等额本息还款多少?(算复利条件下等额还款金额) ...
- 201. Bitwise AND of Numbers Range -- 连续整数按位与的和
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers ...
- C语言知识整理(2):volatile与register
1.volatile volatile是易变的,不稳定的意思,volatile是关键字,是一种类型修饰符,用它修饰的变量表示可以被某些编译器未知的因素更改,比如操作系统.硬件或者其他线程等,遇到这个关 ...
- svn resolve/merge
svn merge http://svn.a.com/branches/20150129_168954_sales-impr_1 svn resolve --accept working web/sr ...
- linux下不能使用shutdown命令
命令查看: #echo $PATH /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/sbin;/ ...
- 使用drawBitmapMesh扭曲图像
Canvas提供了一个drawBitmapMesh(bitmap, meshWidth, meshHeight, verts, vertOffset, colors, colorOffset, pai ...
- iOS产品开发流程
iOS产品开发流程 a.产品经理做需求调研,确定产品需求,编写需求文档 b.产品人员完成产品原型 c.产品经理召开会议(产品,UI,UE,开发,测试,服务器) d.设计人员根据原型设计出一系列UI界面 ...
- P142-1
P142-1.1 登录页面 <%@ page language="java" contentType="text/html; charset=UTF-8" ...
- DP 剪枝
DP其实也是和搜索一样可以有剪枝的,昨晚看到一个超级好的DP剪枝题:(HDU - 5009) N段东东,要染色,每次给一个区间染色需要的花费为 该区间颜色总数的平方. 每一段只能被染一次色.求 最 ...
- sqlite3 SQL常用语句
1. select SELECT LastName,FirstName FROM Persons; SELECT * FROM Persons; 2. where SELECT * FROM Pers ...