題目連接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/數組
題目大意:與122題相似,只是這裏要求買賣次數只能有兩次,計算兩次總共的最大利潤值。ide
法一(超時):計算某一天以前的最大利潤值與某一天以後的最大利潤值,而後用for循環遍歷獲得最大值,時間複雜度是o(n^2),代碼以下:post
1 int res = 0; 2 for(int i = 0; i < prices.length; i++) { 3 int maxPre = 0; 4 int min = Integer.MAX_VALUE; 5 //0 to i-1 6 for(int j = 0; j < i; j++) { 7 if(prices[j] < min) { 8 min = prices[j]; 9 } 10 else if(prices[j] - min > maxPre){ 11 maxPre = prices[j] - min; 12 } 13 } 14 //i to n-1 15 int maxPost = 0; 16 min = Integer.MAX_VALUE; 17 for(int j = i; j < prices.length; j++) { 18 if(prices[j] < min) { 19 min = prices[j]; 20 } 21 else if(prices[j] - min > maxPost){ 22 maxPost = prices[j] - min; 23 } 24 } 25 26 if(maxPre + maxPost > res) { 27 res = maxPre + maxPost; 28 } 29 } 30 return res;
法二(借鑑):動態規劃,利用法一的思路,只是這裏不用for循環嵌套遍歷獲得最大值,而是用兩個數組分別記錄某一天以前的最大利潤值和某一天以後的最大利潤值,而後再另開一個for循環,計算比較獲得最大值。這裏有兩個動規公式:spa
1.數組記錄最大利潤:.net
1)某一天以前:preProfit[i] = max(preProfit[i - 1], prices[i] - min);code
2)某一天以後:postProfit[i] = max(postProfit[i + 1], max - prices[i]);blog
2.for循環計算獲得最大值:res = max(res, preProfit[i] + postProfit[i]);ip
代碼以下(耗時1ms):leetcode
1 int length = prices.length; 2 int[] preProfit = new int[length]; 3 int[] postProfit = new int[length]; 4 //從前日後找,0 to i,用數組記錄每一天i以前所能得到的最大利潤,計算過程與121題相似 5 int minPrice = Integer.MAX_VALUE; 6 int max = 0; 7 for(int i = 0; i < length; i++) { 8 if(prices[i] < minPrice) { 9 minPrice = prices[i]; 10 } 11 else if(prices[i] - minPrice > max) { 12 max = prices[i] - minPrice; 13 } 14 preProfit[i] = max; 15 } 16 //從後往前,i to n-1,用數組記錄每一天i以後所能得到的最大利潤 17 //注意:從後往前找的時候,應該記錄當前位置以後的最大價值,而後將當前位置的價值與最大價值進行比較 18 int maxPrice = Integer.MIN_VALUE; 19 max = 0; 20 for(int i = length - 1; i >= 0; i--) { 21 if(prices[i] > maxPrice) { 22 maxPrice = prices[i]; 23 } 24 else if(maxPrice - prices[i] > max) { 25 max = maxPrice - prices[i]; 26 } 27 postProfit[i] = max; 28 } 29 30 int res = 0; 31 for(int i = 0; i < length; i++) { 32 if(preProfit[i] + postProfit[i] > res) { 33 res = preProfit[i] + postProfit[i]; 34 } 35 } 36 return res;
法三(借鑑):參考:http://blog.csdn.net/u012501459/article/details/46514309解法二。get