小明思考

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

          日歷

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

          相冊

          My blogs

          搜索

          •  

          最新評論

          最佳的股票買賣時間III

          Posted on 2013-04-25 22:22 小明 閱讀(2078) 評論(0)  編輯  收藏 所屬分類: 數據結構和算法
          問題假設你有一個數組包含了每天的股票價格,它的第i個元素就是第i天的股票價格。 

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


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

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

          為了提高效率,這里使用動態規劃,即把中間狀態記錄下來。使用了兩個數組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;        
              }
          主站蜘蛛池模板: 凭祥市| 额敏县| 新巴尔虎右旗| 金沙县| 东丰县| 铁岭市| 临洮县| 汶川县| 沙雅县| 桦甸市| 宜都市| 治多县| 金乡县| 高州市| 萨迦县| 丰台区| 金平| 阿瓦提县| 天祝| 库车县| 岚皋县| 旬邑县| 甘泉县| 清镇市| 百色市| 苏州市| 久治县| 湄潭县| 高唐县| 怀来县| 页游| 平武县| 柳河县| 定结县| 扶沟县| 汽车| 邳州市| 陆河县| 长子县| 武穴市| 丹巴县|