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 }

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

  • 相关阅读:
    Java学习第一周汇报
    Java暑期学习第八天日报
    Java暑期学习第十天日报
    Java暑期学习第十二天日报
    Java学习第二周汇报
    Java暑期学习第九天日报
    0006 列表(ul、ol、dl)
    0015 行高那些事:lineheight
    0016 CSS 背景:background
    HTTP中GET与POST的区别 99%的错误认识
  • 原文地址:https://www.cnblogs.com/hewx/p/4535698.html
Copyright © 2011-2022 走看看