Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

法I:把要求的东西profits设成状态。

第一次:从左往右扫描,同I一样记录下minimum value,不同的是,不仅要知道最大profit,还要记录下每个当前位置的profit(需要一个数组),为了之后与第二次扫描的结果相加。

第二次:从右往左scan,记录下maximum value, 计算profit,再加上之前第一次扫描从0到当前位置的profit,得到总的profit。

时间复杂度O(n) *2

class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty()) return ; int size = prices.size();
int maxProfit = ;
int* profits = new int [size]; //表示从0到i的最大利润
int* profits_from_last = new int [size]; //表示从i到size-1的最大利润 //initial status
profits[] = ;
int minValue = prices[]; //scan from start
for(int i = ; i< size; i++)
{
if(prices[i] < minValue) //save the minimum value
{
minValue = prices[i];
profits[i] = profits[i-];
}
else //caculate the profit from minimum value to currentand compare to previous maximum profit(profits[i-1])
{
profits[i] = max(prices[i]-minValue,profits[i-]);
} } //initial status
profits_from_last[size-] = ;
int maxValue = prices[size-]; //scan from last
for(int i = size-; i >= ; i--)
{
if(prices[i] > maxValue) //save the maximum value
{
maxValue = prices[i];
profits_from_last[i] = profits_from_last[i+];
}
else //caculate the profit from current to maximum value and compare to previous maximum profit(profits_from_last[i+1])
{
profits_from_last[i] = max(maxValue-prices[i],profits_from_last[i+]);
} int profit = profits[i] + profits_from_last[i]; //calculate profits of two transactions
if(profit>maxProfit)
{
maxProfit = profit;
}
}
return maxProfit;
}
};

Note:第二次scan不必存储每个状态,所以只需一个变量存储到目前为止第二次扫描的最大利润。

class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty()) return ; int size = prices.size();
int maxProfit = ;
int* profits = new int [size]; //表示从0到i的最大利润
int* profits_from_last = new int [size]; //表示从i到size-1的最大利润 //initial status
profits[] = ;
int minValue = prices[]; //scan from start
for(int i = ; i< size; i++)
{
if(prices[i] < minValue) //save the minimum value
{
minValue = prices[i];
profits[i] = profits[i-];
}
else //caculate the profit from minimum value to currentand compare to previous maximum profit(profits[i-1])
{
profits[i] = max(prices[i]-minValue,profits[i-]);
} } //initial status
int maxSecondProfits = ;
int maxValue = prices[size-]; //scan from last
for(int i = size-; i >= ; i--)
{
if(prices[i] > maxValue) //save the maximum value
{
maxValue = prices[i];
}
else //caculate the profit from current to maximum value and compare to previous maximum profit(maxSecondProfits)
{
maxSecondProfits = max(maxValue-prices[i],maxSecondProfits);
} int profit = profits[i] + maxSecondProfits; //calculate profits of two transactions
if(profit>maxProfit)
{
maxProfit = profit;
}
}
return maxProfit;
}
};

法II:进一步提升space efficiency。扫描一次,从而不用存储第一次交易的状态。

在扫描的时候,把当前点看作两次交易都完成的点,计算当前最大利润。

然后再依次更新把当前点看作第二次买入点的最大利润,看作第一次卖出点的最大利润,第一次买入点的最大利润,这些都为了在下一个循环用来更新状态。

所以,需要用4个变量存储到当前日为止第1/2次买入/卖出的利润最大值。

时间复杂度O(n)

class Solution {
public:
int maxProfit(vector<int>& prices) {
int dates = prices.size();
if(dates <= ) return ; int hold1 = INT_MIN, hold2 = INT_MIN;//buy stock
int release1 = , release2 = ;//sell stock for(int i = ; i < dates; i++){
release2 = max(release2, hold2+prices[i]);// The maximum if we've just sold 2nd stock so far.
hold2 = max(hold2, release1 - prices[i]); // The maximum if we've just buy 2nd stock so far.
release1 = max(release1, hold1+prices[i]);// The maximum if we've just sold 1nd stock so far.
hold1 = max(hold1, -prices[i]); // The maximum if we've just buy 1st stock so far.
}
return release2;
}
};

123. Best Time to Buy and Sell Stock III (Array; DP)的更多相关文章

  1. LN : leetcode 123 Best Time to Buy and Sell Stock III

    lc 123 Best Time to Buy and Sell Stock III 123 Best Time to Buy and Sell Stock III Say you have an a ...

  2. LeerCode 123 Best Time to Buy and Sell Stock III之O(n)解法

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  3. 【leetcode】123. Best Time to Buy and Sell Stock III

    @requires_authorization @author johnsondu @create_time 2015.7.22 19:04 @url [Best Time to Buy and Se ...

  4. [leetcode]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 ...

  5. 【刷题-LeetCode】123 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. 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 a ...

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

  8. 123. Best Time to Buy and Sell Stock III ——LeetCode

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  9. [LeetCode] 123. Best Time to Buy and Sell Stock III 买卖股票的最佳时间 III

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

随机推荐

  1. RouterOS 设定NAT loopback (Hairpin NAT)回流

    In the below network topology a web server behind a router is on private IP address space, and the r ...

  2. Sublime Text 2 - 性感无比的代码编辑器!程序员必备神器!

    Sublime Text 2 - 性感无比的代码编辑器!程序员必备神器! http://www.iplaysoft.com/sublimetext.html 代码编辑器或者文本编辑器,对于程序员来说, ...

  3. Web Api in Orchard

    Web Api in Orchard Web Api is available in Orchard. You can implement a web api to fit your needs in ...

  4. 洛谷P1415 拆分数列

    题目背景 [为了响应党中央勤节俭.反铺张的精神,题目背景描述故事部分略去^-^] 题目描述 给出一列数字,需要你添加任意多个逗号将其拆成若干个严格递增的数.如果有多组解,则输出使得最后一个数最小的同时 ...

  5. Java笔试基础01

    单例模式主要作用是保证在Java应用程序内,一个类只有一个实例存在. 手写单例 1.较为安全的写法 public class Singleton01{ private static Singleton ...

  6. JoinableQueue---创建可连接的共享进程队列

    创建可连接的共享进程队列.这就像是一个Queue对象,但队列允许项目的使用者通知生产者项目已经被成功处理. 通知进程是使用共享的信号和条件变量来实现的. from multiprocessing im ...

  7. 网站搜索引擎优化SEO策略及相关工具资源

    网站优化的十大奇招妙技 1. 选择有效的关键字: 关键字是描述你的产品及服务的词语,选择适当的关键字是建立一个高排名网站的第一步.选择关键字的一个重要的技巧是选取那些常为人们在搜索时所用到的关键字. ...

  8. wzben的QQ空间

    实习之后没有动过博客了,后续慢慢补.

  9. jpa-jpql-basic-test

    jpql 基本测试 //可以使用 JPQL 完成 UPDATE 和 DELETE 操作. @Test public void testExecuteUpdate(){ String jpql = &q ...

  10. JAVA JDBC 简单的增删改查

    package jdbc_util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepar ...