小明思考

          Just a software engineer
          posts - 124, comments - 36, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          日歷

          <2013年4月>
          31123456
          78910111213
          14151617181920
          21222324252627
          2829301234
          567891011

          相冊

          My blogs

          搜索

          •  

          最新評論

          問題假設(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;        
              }
          主站蜘蛛池模板: 牙克石市| 二手房| 尚义县| 年辖:市辖区| 额敏县| 营山县| 天津市| 宜黄县| 乐都县| 北宁市| 安远县| 万盛区| 茂名市| 吉木乃县| 福州市| 忻州市| 南皮县| 阳城县| 哈巴河县| 青铜峡市| 马尔康县| 罗甸县| 夏邑县| 虞城县| 莎车县| 洪雅县| 阜城县| 日照市| 肃南| 个旧市| 安溪县| 班戈县| 集安市| 阳山县| 西城区| 夏津县| 万盛区| 都江堰市| 福海县| 洪泽县| 福建省|