【LeetCode OJ】Best Time to Buy and Sell Stock III

时间:2022-09-23 16:08:55

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

  1. prices[i] <= prices[s0], for i = b0, ..., n-1
  2. 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:

  1. b0 <= s1 <= s0, we prove it by contradiction:
    1. if s1 < b0 (-----s1--b0-----s0------), then (b2,s2) could be replaced by (b0, s0).
    2. if s1 > s0 (----b0----s0--s1--------), then (b1, s1) could be replaced by (b0, s0).
  2. b0 <= b2 <= s0, we prove it by contradiction:
    1. if b2 < b0 (---b2----b0-------s0---), then (b2, s2) could be replaced by (b0, s0).
    2. if b2 > s0 (---------b0----s0--b2--), then (b1, s1) could be replaced by (b0, s0).
  3. For b1 < s1, since s1 <= s0, then s1 could be b0, since prices[b0] <= prices[i] for i = 0,...,s0.
  4. 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的更多相关文章

  1. 【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 ...

  2. 【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 ...

  3. LeetCode OJ 123&period; 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 ...

  4. 【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 ...

  5. 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 ...

  6. 【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 ...

  7. LeetCode OJ 122&period; 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 ...

  8. LeetCode OJ 121&period; 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 ...

  9. 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 ...

随机推荐

  1. miniui中的相关问题

    miniui中的datagrid,若需要为其中表格设置值,则: 必须保证查出来的json中字段对应field,且json的格式必须为: {“data”:[{"id":"0 ...

  2. apscheduler 排程

    https://apscheduler.readthedocs.org/en/v2.1.2/cronschedule.html 参数 说明 year 4位年 month 月份1-12 day 日:1- ...

  3. UVa 10905 Children&&num;39&semi;s Game

    注意!这不是单纯的字典序排序,比如90.9,应该是990最大 对字符串排序蛋疼了好久,因为别人说string很慢,所以一直没有用过. 看别人用string还是比较方便的,学习一下 对了,这里的cmp函 ...

  4. solr查询字段为空值&comma;删除字段空值的方法

    1. 例,我想查找内容字段content为空值的文档,看看文档有多少?执行如下查询. http://127.0.0.1:11100/solr/province/select?q=-(content:* ...

  5. SQL server 数据库——数学函数、字符串函数、转换函数、时间日期函数

    数学函数.字符串函数.转换函数.时间日期函数 1.数学函数 ceiling()--取上限  select ceiling(oil) as 油耗上限 from car floor()--取下限 sele ...

  6. 【转】C语言中内存分配

    原文:C语言中内存分配 在任何程序设计环境及语言中,内存管理都十分重要.在目前的计算机系统或嵌入式系统中,内存资源仍然是有限的.因此在程序设计中,有效地管理内存资源是程序员首先考虑的问题. 第1节主要 ...

  7. linux安装lamp环境&lpar;linux&plus;apache&plus;mysql&plus;php&rpar;

    源码安装 本次使用 Centos7.2 MySQL5.7.22 Apache2.4.37 PHP5.6.38 安装Apache 安装httpd和所需依赖:gcc, apr, apr-util,apr- ...

  8. CentOS 7 搭建Squid代理服务器

    Squid安装 官方地址:http://www.squid-cache.org/ [root@DaMoWang ~]# -r6d8f397.tar.gz [root@DaMoWang ~]# -r6d ...

  9. error MSB3073 解决办法

    发现拷贝命令编译错误,查看输出列表发现时无法找到相应的路径. 1.顺着这个思路第一个想到的是中文路径的问题,先修改了盘符的中文名称,发现还是无法解决具体的问题. 2.后来反复查阅网上的资料,发现帮助并 ...

  10. centos中安装tomcat&plus;jenkins

    1) 安装tomcat 安装tomcat6: http://www.cnblogs.com/itech/p/3506011.html 安装tomcat7: http://www.cnblogs.com ...