【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 ...
随机推荐
- Uva-------(11462) Age Sort(计数排序)
B Age Sort Input: Standard Input Output: Standard Output You are given the ages (in years) of all ...
- nyoj------20吝啬的国度
吝啬的国度 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 在一个吝啬的国度里有N个城市,这N个城市间只有N-1条路把这个N个城市连接起来.现在,Tom在第S号城市 ...
- 张艾迪(创始人):世界级天才女孩Eidyzhang
让整个世界与我们一同解读世界第一天才:Eidyzhang 她改变了整个世界.她的故事也激励了整个世界的不论亚洲.欧洲.非洲.南美州.北美洲.南极洲 天才Eidyzhang的故事激励了整个世界不论黑人. ...
- HtmlHelper—DropDownList:SelectList、SelectListItem
前言 在项目中经常使用到DropDownList来显示数据库中的数据,典型的例子为为某书籍选择所属类型. 使用SelectList来实现: 实现一: Controller 代码 SelectList ...
- 转载:完全卸载oracle11g步骤
完全卸载oracle11g步骤: 1. 开始->设置->控制面板->管理工具->服务 停止所有Oracle服务. 2. 开始->程序->Oracle - OraHo ...
- static初始化问题探究
两个小示例 demo1 package containers; public class TempTest { static{ a= 1; // System.out.println(a); } st ...
- ViewPager滑动页面的实现方法
package com.lixu.pagerview; import java.util.ArrayList; import android.app.Activity; import android. ...
- js基础之数组
数组方法 添加: push arr.push();//尾部添加 unshift arr.unshift();//头部添加 删除: pop arr.pop();//尾部删除 shift arr.shif ...
- 使用read write 读写socket
一旦,我们建立好了tcp连接之后,我们就可以把得到的fd当作文件描述符来使用. 由此网络程序里最基本的函数就是read和write函数了. 写函数: ssize_t write(int fd, con ...
- 百胜集团李磊:BPM实现业务流程全过程无缝链接
作为全球最大的餐饮企业之一,百胜集团在形成规模化连锁经营效应的同时,战略地利用信息化手段,强化管理和运营水平,打造企业的核心竞争力.通过流程梳理,百胜集团实现了以规模化.规范化.信息化和现代化为主题的 ...