Thursday, November 26, 2015

[leetcode]Best Time to Buy and Sell stock series

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) return 0;
        int currentMin = prices[0];
        int result = 0;
        for (int i = 1; i < prices.length; i++){
            result = Math.max(result, prices[i]-currentMin);
            currentMin = Math.min(currentMin, prices[i]);
        }
        
        return result;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        int currentStart = 0;
        int currentEnd = 0;
        int sum = 0;
        for (int i = 1; i < prices.length; i++){
            if (prices[i] < prices[i-1]){
                sum += (prices[currentEnd]-prices[currentStart]);
                currentStart = currentEnd = i;
            }else{
                currentEnd = i;
            }
        }
        sum += (prices[currentEnd]-prices[currentStart]);
        return sum;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) return 0;
        int[] profit = new int[prices.length];
        int[] profit_r = new int[prices.length];
        findMaxI(prices, profit);
        findMaxII(prices, profit_r);
        int max = 0;
        for (int i = 0; i < prices.length; i++){
            max = Math.max(profit[i]+profit_r[i], max);
        }
        return max;
    }
    
    private void findMaxII(int[]prices, int profit[]){
        int currentMax = prices[prices.length-1];
        int last = profit[prices.length-1];
        for (int i = prices.length-2; i >= 0; i--){
            profit[i] += Math.max(profit[i+1], currentMax-prices[i]);
            currentMax = Math.max(prices[i], currentMax);
        }
        return;
    }
    
    private void findMaxI(int[]prices, int profit[]){
        int currentMin = prices[0];
        for (int i = 1; i < prices.length; i++){
            profit[i] = Math.max(profit[i-1], prices[i]-currentMin);
            currentMin = Math.min(prices[i], currentMin);
        }
        return;
    }
}

No comments:

Post a Comment