JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

 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 }

 

 

posted on 2013-11-11 12:56  JasonChang  阅读(183)  评论(0编辑  收藏  举报