zoukankan      html  css  js  c++  java
  • LeetCode 123 Best Time to Buy and Sell Stock III

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

    //http://yucoding.blogspot.com/2012/12/leetcode-question-10-best-time-to-buy.html
    //http://www.cnblogs.com/springfor/p/3877068.html

    就是分成两段一段是(0-i)一次买卖,一段是(i+1 -- len-1)一次买卖。上述两次买卖的最大利益。。

    动态规划,左数组保存,0-i的时候一次交易的最大收益。(从0就是最左边开始到某个位置i:一次买卖最大收益)

                 右数组保存,i-最后位置的时候,就是i到len-1时候的最大收益。(从某个位置i到最后的位置len-1:一次买卖的最大收益)

           然后找到i点的最大收益:就是从i点之前的一次交易加上i点之后的一次交易的最大收益(按照题目要求的两次买卖)。

     1 public class bestbuysell123 {
     2     public int maxProfit(int[] prices){
     3         if(prices.length==0 || prices==null){
     4             return 0;
     5         }
     6         
     7         int len = prices.length;
     8         int[] left = new int[len];
     9         int[] right = new int[len];
    10         
    11         left[0] = 0;
    12         int low = prices[0];
    13         for(int i = 1; i<len; i++){
    14             low = Math.min(low, prices[i]);
    15             left[i] = Math.max(left[i-1], prices[i]-low);
    16         }    
    17         
    18         right[0]=0;
    19         int hight = prices[len-1];
    20         for(int i =len-2; i>=0; i--){
    21             hight = Math.max(hight, prices[i]);
    22             right[i] = Math.max(right[i+1], hight-prices[i]);
    23         }
    24         
    25         int maxfit = 0;
    26         for(int i = 0; i < len; i++){
    27             maxfit=Math.max(maxfit, left[i]+right[i]);
    28         }
    29         return maxfit;
    30     }
    31 }

    想了半天,想明白了就好了。

  • 相关阅读:
    怎样编写一个Photoshop滤镜(1)
    蜂窝状网格的定位方法
    【转载】[TC]飞船动画例子《C高级实用程序设计》
    【完全随笔】用户体验和设计
    在 WinCe 平台读写 ini 文件
    关于携带完整 alpha 通道图标的技术研究
    【转载】When should static_cast, dynamic_cast and reinterpret_cast be used?
    怎样编写一个Photoshop滤镜(3) Scripting Plugins
    配电网WebGIS研究与开发[5]
    配电网WebGIS研究与开发[4]
  • 原文地址:https://www.cnblogs.com/hewx/p/4535698.html
Copyright © 2011-2022 走看看