【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 ...
随机推荐
- 更准确的mysql全文索引
MYSQL自带的全文索引在查找数据的时候,有非常多的限制,如字符少于3个不能搜索,常用字不能搜索 但mysql 的like进行查询的时候又非常的慢 但你需要用到比较准确的查询的时候,要么不用mysql ...
- Trapping Rain Water [LeetCode]
Problem Description: http://oj.leetcode.com/problems/trapping-rain-water/ Basic idea: Get the index ...
- Visual Studio 2012出现“无法访问T-SQL组件和安装了不兼容伯 DacFx版本”的解决办法
参考:Visual Studio 2012出现“无法访问T-SQL组件和安装了不兼容伯 DacFx版本”的解决办法 Vs2012的下载地址: https://msdn.microsoft.com/en ...
- HTML第一部分
HTML 内容(hyper text markup language,超文本标记语言) CSS 网页美化 Javacript 脚本语言 第一部分 HTML <html ...
- hdu 1520
Anniversary party Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- 史上最全的 Java 新手问题汇总
史上最全的 Java 新手问题汇总 Java是目前最流行的编程语言之一——它可以用来编写Windows程序或者是Web应用,移动应用,网络程序,消费电子产品,机顶盒设备,它无处不在. 有超过30亿 ...
- PostgreSQL数据库系统优点
PostgreSQL 是世界上可以获得的最先进的开放源码的数据库系统, 它提供了多版本并行控制,支持几乎所有 SQL 构件(包括子查询,事务和用户定 义类型和函数), 并且可以获得非常广阔范围的(开发 ...
- Query的选择器中的通配符[id^='code']或[name^='code']
1.选择器 (1)通配符: $("input[id^='code']");//id属性以code开始的所有input标签 $("input[id$='code'] ...
- HDU 2181 哈密顿绕行世界问题 dfs 难度:1
http://acm.hdu.edu.cn/showproblem.php?pid=2181 只有20个城市,而且每个点的度数恰好是3,也就意味着,对于即将进入环中的点,入度1,出度2,下一个点只有两 ...
- Oracle 11g 安装
1.Oracle 11g安装: http://www.cnblogs.com/qianyaoyuan/archive/2013/05/05/3060471.html 2.安装完Oracle数据库,给s ...