题目:

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

代码:

class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()) return ;
const int len = prices.size();
vector<int> l(len,),r(len,);
// from left to right
l[] = ;
int l_min = prices[];
for ( int i = ; i < l.size(); ++i )
{
l_min = std::min(l_min, prices[i]);
l[i] = std::max(l[i-], prices[i]-l_min);
}
// from right to left
r[len-] = ;
int r_max = prices[len-];
for ( int i = len-; i >= ; --i )
{
r_max = std::max(r_max, prices[i]);
r[i] = std::max(r[i-], r_max-prices[i]);
}
// travseral the best two times
int max_profit = ;
for ( int i = ; i < prices.size(); ++i )
{
max_profit = std::max(max_profit, l[i]+r[i]);
}
return max_profit;
}
};

tips:

此题说最多交易两次,求最大获利。

直觉的想法就是,把整个时间段分割成两部分( 共有prices.size()种分类方法 );分好后分别求两部分各自的最大值;这种算法是O(n²)时间复杂度的。

模仿之前求过的largest rectangle in histogram这道题的思路,能否利用dp思想,把算过的中间结果都存起来,把时间复杂度降低到O(n)。

想到这个思路就比较明确了:

1. 从左向右走一遍,l[i]存放0~i最多交易1次获利最大的值

2. 从右向左走一遍,r[i]存放i~prices.size()-1最多交易一次获利的最大值

3. 遍历数组l和数组r,通过遍历每种分割情况下的最大获利,并最终获得最终的最大获利值。

这里还有个细节可能会产生疑义:如果以第i天作为分割点,那么这第i天是算到前半截还是后半截呢?

这里分两种情况:

1. 如果“前半截的最大利润”和“后半截的最大利润”只有一截涉及到了第i天,显然l[i]+r[i]这个算法是没问题的

2. 如果“前”、“后”两截都涉及到了第i天呢?这时候有两种理解方法:

  2.1 前后交易两次:前半截的某一天买入,第i天卖了,挣一笔;第i天卖完又买入了,到后面的某一天又卖了,挣第二笔。两笔加起来最大。

  2.2 前后交易一次:前半截的某一天买入,第i天虽然卖了获利最大,但是不卖,留着;等到后面的某一天发现获利最大,直接挣一笔最大的,同样获利最大。

因此,无论按照哪种理解方法,l[i]+r[i]都是合理的,不会因为第i天作为分割点而产生影响。

=====================================================

第二次过这道题,思路上有个地方没有理清(红字),在当天可以选择交易或者不交易,如果不交易那么等于左边(或右边)相邻元素的值。

class Solution {
public:
int maxProfit(vector<int>& prices) {
if ( prices.empty() ) return ;
vector<int> l(prices.size(), );
vector<int> r(prices.size(), );
// l
int minPrices = prices[];
for ( int i=; i<prices.size(); ++i )
{
minPrices = min(prices[i], minPrices);
l[i] = max(l[i-1], prices[i]-minPrices);
}
// r
int maxPrices = prices[prices.size()-];
for ( int i=prices.size()-; i>=; --i )
{
maxPrices = max(maxPrices, prices[i]);
r[i] = max(r[i+1], maxPrices - prices[i]);
}
// l to r
int ret = ;
for ( int i=; i<prices.size(); ++i )
{
ret = max(ret, l[i]+r[i]);
}
return ret;
}
};

【Best Time to Buy and Sell Stock III 】cpp的更多相关文章

  1. 【Best Time to Buy and Sell Stock II】cpp

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

  2. leetcode 【 Best Time to Buy and Sell Stock III 】python 实现

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

  3. leetcode 【 Best Time to Buy and Sell Stock II 】python 实现

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

  4. 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】

    [121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Say you have ...

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

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

  7. 【刷题-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 ...

  8. 27. Best Time to Buy and Sell Stock && Best Time to Buy and Sell Stock II && Best Time to Buy and Sell Stock III

    Best Time to Buy and Sell Stock (onlineJudge: https://oj.leetcode.com/problems/best-time-to-buy-and- ...

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

随机推荐

  1. js对jsonArray的操作

    上一篇写了关于java中Gson对jsonArray的排序处理,这里介绍js中对jsonArray处理, <!DOCTYPE html> <html> <head> ...

  2. javascript的Array.prototype.map()和jQuery的jQuery.map()

    两个方法都可以根据现有数组创建新数组,但在使用过程中发现有些不同之处 以下面这个数据为例: var numbers = [1, 3, 4, 6, 9]; 1. 对undefined和null的处理 a ...

  3. 怎么旋转PDF文件的方向并保存成功

    http://jingyan.baidu.com/article/59a015e39d7802f79488651e.html PDF格式的文档是非常普遍的一种阅读电子书格式,基本上非常好用了,不过有时 ...

  4. C++ vector类详解

    转自http://blog.csdn.net/whz_zb/article/details/6827999 vector简介 vector是STL中最常见的容器,它是一种顺序容器,支持随机访问.vec ...

  5. windows xp professional 序列号(密钥)及百度网盘下载地址

    HH7VV-6P3G9-82TWK-QKJJ3-MXR96 https://pan.baidu.com/share/link?uk=4247247642&shareid=500360

  6. 富文本编辑器Ueditor的使用

    1.下载:http://ueditor.baidu.com/website/download.html. 2.解压,并放到项目webapp下. 3.jsp页面的配置. 4.配置根路径. 5.页面展示: ...

  7. TFS看板的迭代规划

    故事点 故事点更多体现的是用户情景或者bug的规模,采用斐波拉契数列(1,2,3,5,8,13)这样的数字表示,包含如下内容: 相对工作量 复杂度 风险和不确定性 相对工作量 下面演示一个Case来说 ...

  8. hdu-1874 畅通工程续---模板题

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1874 题目大意: 求起点到终点的最短距离 解题思路: 注意重边,其他的就是模板 #include&l ...

  9. CUDA开发:了解设备属性

    原文链接 今天介绍一下CUDA设备的相关属性,只有熟悉了硬件是相关属性,是怎么工作的,就能写出更适合硬件工作的代码.cudaDeviceProp这个结构体记录了设备的相关属性. struct cuda ...

  10. django+xadmin在线教育平台(一)

    大家好,此教程为在慕学网的实战教程Python升级3.6 强力Django+杀手级Xadmin打造在线教育平台的学习笔记,不对望指正! 使用Django+Xadmin打造在线教育平台(Python2, ...