123. Best Time to Buy and Sell Stock III (Array; DP)
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)的更多相关文章
- 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 ...
- 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 ...
- 【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 ...
- [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 ...
- 【刷题-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 ...
- 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 ...
- 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 ...
- 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 ...
- [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 ...
随机推荐
- fiddler链接手机
fiddler设置: 见python_request-上海悠悠 哪里有说 手机和window设置: 1,要把电脑防火墙关掉 2.手机访问http://ip:port安装Fiddler证书,特别注意IO ...
- C# 窗体控件输入框大写
// 将 a-z 改为 A-Z // 'a' 'z' && e.KeyChar <= ) e.KeyChar = ();
- 阿里云启用IPV6
ping过别人的IPv6网址之后,可以确定,局域网是不支持IPv6的.所以要使用隧道技术建立两台机器之间的IPv6连接 1.发现测试用服务器上没有IPv6地址.所以测试服务器的内核应该是没有IPv6模 ...
- 联想Z510升级BCM94352HMB刷网卡白名单曲折经历
联想Z510笔记本:CPU I7 4702MQ没毛病 :内存4G DDR3不上虚拟机办公足够用: 硬盘升级为SSD240G足够用:有线网卡100M,真是垃圾,不过有线网卡是主板上的芯片,这个我可动不了 ...
- MongoDB——更新操作(Update)c#实现
c#实现 Mongodb存储[文档局部更新] 如下: 递归更新字段 ,构建UpdateDefinition /// <summary> /// 构建更新操作定义 /// &l ...
- 线程使用方法 锁(lock,Rlock),信号了(Semaphore),事件(Event),条件(Ccndition),定时器(timer)
2线程的使用方法 (1)锁机制 递归锁 RLock() 可以有无止尽的锁,但是会有一把万能钥匙 互斥锁: Lock() ...
- django之python网站开发基础
原文:http://www.cnblogs.com/feixuelove1009/p/5823135.html 一.Django简介 百度百科:开放源代码的Web应用框架,由Python语言编写... ...
- python基础补充内容
知识内容: 1.三元运算表达式 2.python代码编写规范 3.模块导入与使用 4.python文件名 5.python脚本的"__name__"属性 6.python之禅 一. ...
- HTML5 Canvas ( 画一个五角星 ) lineJoin miterLimit
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 程序员必看:给你一份详细的Spring Boot知识清单
在过去两三年的Spring生态圈,最让人兴奋的莫过于Spring Boot框架.或许从命名上就能看出这个框架的设计初衷:快速的启动Spring应用.因而Spring Boot应用本质上就是一个基于Sp ...