Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int len = prices.length;
 4         if(len==0) return 0;
 5         int res = 0;
 6         int[] profit = new int[len];
 7         int min = Integer.MAX_VALUE;
 8         int maxProfitBeforeI = 0;
 9         for(int i=0;i<len;i++){
10             int cur = prices[i];
11             if(min>cur){
12                 min = cur;
13             }
14             if(maxProfitBeforeI<cur-min){
15                 maxProfitBeforeI = cur-min;
16             }
17             profit[i] = maxProfitBeforeI;
18         }
19         int max = Integer.MIN_VALUE;
20         for(int i=len-1;i>=0;i--){
21             int cur = prices[i];
22             if(max<cur){
23                 max = cur;
24             }
25             if(max-cur>0){
26                 res = Math.max(res,profit[i]+max-cur);
27             }
28         }
29         return res;
30     }
31 }
View Code

 

posted @ 2014-02-19 05:30  krunning  阅读(132)  评论(0编辑  收藏  举报