Best Time to Buy and Sell Stock III

前后两遍遍历,算出当前位置之前和之后的最大利润。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         
 4         if(prices == null || prices.length == 0)
 5             return 0;
 6             
 7         int[] max = new int[prices.length];
 8         int min = prices[0];
 9         int result = 0;
10         
11         for(int i = 1; i < prices.length; i++){
12             min = Math.min(min, prices[i]);
13             max[i] = Math.max(max[i-1], prices[i] - min);
14         }
15         
16         int peek = Integer.MIN_VALUE;
17         for(int i = prices.length-1; i >= 0; i--){
18             
19             peek = Math.max(prices[i],peek);
20             result = Math.max(result, peek - prices[i] + max[i]);
21         }
22         return result;
23     }
24 }
原文地址:https://www.cnblogs.com/jasonC/p/3417722.html