小明思考

          Just a software engineer
          posts - 124, comments - 36, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
          問題假設(shè)你有一個數(shù)組包含了每天的股票價格,它的第i個元素就是第i天的股票價格。 

          設(shè)計一個算法尋找最大的收益。你可以最多進(jìn)行兩次交易。
          注意:你不能同時進(jìn)行多次交易,也就是說你買股票之前,必須賣掉手中股票。


          分析:
          這道題相比之前的兩道題,難度提高了不少。

          因為限制了只能交易兩次,所以我們可以把n天分為兩段,分別計算這兩段的最大收益,就可以得到一個最大收益。窮舉所有這樣的分法,就可以得到全局的最大收益。

          為了提高效率,這里使用動態(tài)規(guī)劃,即把中間狀態(tài)記錄下來。使用了兩個數(shù)組profits,nprofits分別記錄從0..i和i..n的最大收益。

          代碼如下:

          public int maxProfit(int[] prices) {
                  int days = prices.length;
                  if(days<2){
                      return 0;
                  }
                  int[] profits = new int[days];
                  int min = prices[0];
                  int max = min;
                  for(int i=1;i<days;++i){
                      int p = prices[i];
                      if(min>p){
                          max = min = p;
                      }
                      else if(max<p){
                          max = p;
                      }
                      int profit = max - min;
                      profits[i] = (profits[i-1]>profit)?profits[i-1]:profit;
                  }
                  
                  int[] nprofits = new int[days];
                  nprofits[days-1] = 0;
                  max = min = prices[days-1];
                  for(int i=days-2;i>=0;--i){
                      int p = prices[i];
                      if(min>p){
                          min =p;
                      }
                      else if(max<p){
                          max = min = p;
                      }
                      int profit = max - min;
                      nprofits[i] = (nprofits[i+1]>profit)?nprofits[i+1]:profit;
                  }
                  
                  int maxprofit = 0;
                  
                  for(int i=0;i<days;++i){
                      int profit = profits[i]+nprofits[i];
                      if(maxprofit<profit){
                          maxprofit = profit;
                      }
                  }
                  
                  return maxprofit;        
              }
          主站蜘蛛池模板: 德庆县| 南乐县| 玉树县| 大田县| 古浪县| 罗江县| 麻栗坡县| 灵璧县| 民权县| 同仁县| 新民市| 内黄县| 松潘县| 尉犁县| 南平市| 云和县| 太仆寺旗| 富阳市| 佳木斯市| 肃南| 张家川| 新邵县| 苍梧县| 晋江市| 镇原县| 灵山县| 阿拉善盟| 玛多县| 凌源市| 九龙坡区| 婺源县| 亚东县| 盘山县| 江口县| 商南县| 万全县| 虹口区| 宁德市| 五河县| 建瓯市| 江阴市|