Tuesday, February 26, 2013

[LeetCode] Best Time to Buy and Sell Stock III

Thought: 
Divide the array into two parts, find two profits, and add them together.

Code:
public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for(int i = 0; i < prices.length ; i++){
            if( forwardProfit(prices,i) + backwardProfit(prices,i) > profit ){
                profit = forwardProfit(prices,i) + backwardProfit(prices,i);
            }
        }
        return profit;     
    }
    public int forwardProfit(int[] prices, int n){
        if(prices.length==0) return 0;
        int min = prices[0] ;
        int profit = 0;
       
        for(int i = 0; i < n; i++){
            if( prices[i] < min ){
                min = prices[i];
            }else if( prices[i] - min > profit ){
                profit = prices[i] - min;
            }
        }
        return profit; 
    }
    public int backwardProfit(int[] prices, int n){
        if(prices.length==0) return 0;
        int max = prices[prices.length-1] ;
        int profit = 0;
       
        for(int i = prices.length - 1; i > n - 1; i--){
            if( prices[i] > max ){
                max = prices[i];
            }else if( max - prices[i] > profit ){
                profit = max - prices[i];
            }
        }
        return profit;
    }
}

No comments:

Post a Comment