1.题目描述

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

2.解法分析

限定了交易次数之后题目就需要我们略微思考一下了,由于有两次交易的机会,那么我们选定一个时间点ti,将此时间点作为两次交易的支点的话,必然有:

      t0….ti之内满足最佳交易原则,ti-tn天也满足最佳交易原则,那么这就是一个动态规划的策略了,于是有下面的代码:

 

class Solution {

public:

    int maxProfit(vector<int> &prices) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(prices.size() <=1)return 0;

        vector<int>::iterator iter;

 

    

        for(iter=prices.begin();iter!=prices.end()-1;++iter)

        {

            *iter = *(iter+1) - *iter;

        }

        

        prices.pop_back();

        

        vector<int>accum_forward;

        vector<int>accum_backward;

        

        int max = 0;

        int subMax = 0;

        

        for(iter=prices.begin();iter!=prices.end();++iter)

        {

            subMax += *iter;

            if(subMax > max)max=subMax;

            else

                if(subMax<0)subMax = 0;

                

            accum_forward.push_back(max);

        }

        

        vector<int>::reverse_iterator riter;

        

        max =0 ;

        subMax = 0;

        for(riter=prices.rbegin();riter!=prices.rend();++riter)

        {

            subMax +=*riter;

            if(subMax >max)max = subMax;

            else

                if(subMax<0)subMax=0;

                

            accum_backward.push_back(max);

        }

    

        max =0;

        int len = accum_forward.size();

        for(int i=0;i<len-1;++i)

        {

            if((accum_forward[i]+accum_backward[len-i-2])>max)    

                max = accum_forward[i]+accum_backward[len-i-2];

        }

        

        return max>accum_forward[len-1]?max:accum_forward[len-1];

        

    }

};

 

ps:做完题之后提交,发现老是AC不了,有个case总是解决不了,本来以为是自己代码写得有问题,检查了半天没发现错误,于是开始看别人怎么写,结果发现别人AC的代码也过不了,猜想可能系统还是做得不完善,应该是后台的线程相互干扰了,过了一段时间果然同样的代码又可以AC了。在这段过程中,看别人写的代码,发现了一个比我简洁一些的写法,虽然我么你的复杂度是一样的,但是此君代码量比我的小一点,以后学习学习,另外,一直不知道vector还可以预先分配大小,从这个代码里面也看到了,算是有所收获。附代码如下:

class Solution {

public:

    int maxProfit(vector<int> &prices) {

        // null check

        int len = prices.size();

        if (len==0) return 0;

 

        vector<int> historyProfit;

        vector<int> futureProfit;

        historyProfit.assign(len,0);

        futureProfit.assign(len,0);

        int valley = prices[0];

        int peak = prices[len-1];

        int maxProfit = 0;

 

        // forward, calculate max profit until this time

        for (int i = 0; i<len; ++i)

        {

            valley = min(valley,prices[i]);

            if(i>0)

            {

                historyProfit[i]=max(historyProfit[i-1],prices[i]-valley);

            }

        }

 

        // backward, calculate max profit from now, and the sum with history

        for (int i = len-1; i>=0; --i)

        {

            peak = max(peak, prices[i]);

            if (i<len-1)

            {

                futureProfit[i]=max(futureProfit[i+1],peak-prices[i]);

            }

            maxProfit = max(maxProfit,historyProfit[i]+futureProfit[i]);

        }

        return maxProfit;

    }

 

};

leetcode—Best Time to Buy and Sell stocks III的更多相关文章

  1. LeetCode: Best Time to Buy and Sell Stock III 解题报告

    Best Time to Buy and Sell Stock IIIQuestion SolutionSay you have an array for which the ith element ...

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

  3. [LeetCode] Best Time to Buy and Sell Stock III

    将Best Time to Buy and Sell Stock的如下思路用到此题目 思路1:第i天买入,能赚到的最大利润是多少呢?就是i + 1 ~ n天中最大的股价减去第i天的. 思路2:第i天买 ...

  4. LeetCode: Best Time to Buy and Sell Stock III [123]

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

  5. [Leetcode] Best time to buy and sell stock iii 买卖股票的最佳时机

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

  6. [leetcode]Best Time to Buy and Sell Stock III @ Python

    原题地址:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 题意: Say you have an array ...

  7. leetcode -- Best Time to Buy and Sell Stock III TODO

    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——Best Time to Buy and Sell Stock III

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

  9. LeetCode——Best Time to Buy and Sell Stock III (股票买卖时机问题3)

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

随机推荐

  1. Delphi逆向

    Delphi反汇编内部字符串处理函数/过程不完全列表 名称 参数 返回值 作用 等价形式 / 备注 _PStrCat EAX :目标字符串 EDX :源字符串 EAX 连接两个 Pascal 字符串 ...

  2. MySQL性能优化的21个最佳实践

    http://www.searchdatabase.com.cn/showcontent_38045.htm MySQL性能优化的21个最佳实践 1. 为查询缓存优化你的查询 大多数的MySQL服务器 ...

  3. 关于PYTHON的反射,装饰的练习

    从基本概念,简单例子才能慢慢走到高级一点的地方. 另外,PYTHON的函数式编程也是我很感兴趣的一点. 总体而言,我觉得OOP可以作大的框架和思路,FP能作细节实现时的优雅牛X. ~~~~~~~~~~ ...

  4. 多线程 (五)NSOperation

    NSOperation是对GCD的分装,OC语言,更简单方便 NSOperation和NSOperationQueue一起使用也能实现多线程编程 基本步骤: 将操作封装到一个NSOperation对象 ...

  5. Spring MVC 与 web开发

    转载:http://coderbee.net/index.php/java/20140719/959 项目组用了 Spring MVC 进行开发,觉得对里面的使用方式不是很满意,就想,如果是我来搭建开 ...

  6. Android四大基本组件

    Android四大基本组件分别是 Activity:整个应用程序的门面,负责与用户进行交互. Service:承担大部分工作. Content Provider内容提供者:负责对外提供数据,并允许需要 ...

  7. photoshop:制作木板木纹

    1.设置颜色为木头相近颜色 2.滤镜->渲染->云彩 3.滤镜->杂色->添加杂色 4.滤镜->模糊->动感模糊 5.用矩形选取选取某块区域 6.滤镜->扭曲 ...

  8. Android安全问题 抢先接收广播 - 内因篇之广播接收器注册流程

    导读:本文说明系统是如何注册动态广播以及静态广播,这里主要注意其注册的顺序 这篇文章主要是针对我前两篇文章 android安全问题  抢先开机启动 - 结果篇 android安全问题  抢先拦截短信 ...

  9. poj 1080 Human Gene Functions(dp)

    题目:http://poj.org/problem?id=1080 题意:比较两个基因序列,测定它们的相似度,将两个基因排成直线,如果需要的话插入空格,使基因的长度相等,然后根据那个表格计算出相似度. ...

  10. UVa 1637 (概率) Double Patience

    题意: 一共有9堆牌,每堆牌四张.每次可以取堆顶点数相同的两张牌,如果有多种方案则选取是随机的. 如果最后将所有牌取完,则视为游戏胜利,求胜利的概率. 分析: 用一个九元组表示状态,分别代表每堆牌剩余 ...