【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 ...
随机推荐
- Qt之Concurrent Map和Map-Reduce
简述 QtConcurrent::map().QtConcurrent::mapped()和QtConcurrent::mappedReduced()函数在一个序列中(例如:QList或QVector ...
- WMI远程访问问题解决方法
WMI 全称为:Microsoft Windows Management Instrumentation (WMI) 按微软的介绍大致如下: WMI 是 Microsoft 主要的针对 W ...
- Linux基础: 一切都是文件
一切都是文件 创建系统配置交换分区(用作虚拟内存)加上单根树 file 文件名 查看文件类型 uname 查看系统版本 bin binary二进制文件 所有用户可用 系统可执行命令的二进制文件(c ...
- android入门之: SharedPreferences
读取数据: 保存数据: +++++++++++++++++++方法详解++++++++++++++++++++++++++++++ SharedPreferences综述: 使用getSharedPr ...
- Eclipse启动tomcat 报“ A child container failed during start”
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]] at org.ap ...
- Oracle后台进程
后台进程简介 启动例程时,Oracle不仅会分配SGA,还会启动后台进程:关闭例程时,Oracle不仅会释放SGA所占用的内存空间,而且还会释放后台进程所占用的Cpu和内存资源.Oracle提供了很多 ...
- Android开发--TextView的应用
1.概述 TextView主要用于Activity中文本的应用.其中layout中xml文件(activity)设置文本的宽度,高度,ID:values中strings.xml设置文本内容. Text ...
- Axis2 webservice入门--开发环境搭建,概念理解
关于webservice的概念,网上有各种解释,但是不太好懂. 可以这样理解:1.一个webservice就是一个“功能”,只是这个功能是别人写好的,被放在别人的网站上. ...
- centos 5.8 64位系统安装 mysql5.6
mysql5.5以上的版本编译需要 cmake 1 .安装cmake wget http://www.cmake.org/files/v2.8/cmake-2.8.10.2.tar.g ...
- 元数据和DbUtils
使用元数据可以在jdbc中获取数据库的定义,例如:数据库.表.列的定义信息. 在jdbc中可以使用: 数据库元数据.参数元数据.结果集元数据. 1.DataBaseMetaData对象 Connect ...