Saturday, November 14, 2015

[leetcode] Best Time to Buy and Sell Stock

Just calm down and make sure I get two pointers right.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) return 0;
        int minIndex = 0;
        int maxIndex = 0;
        int result = 0;
        for (int i = 1; i < prices.length; i++){
            if (prices[i] < prices[minIndex]){
                minIndex = maxIndex = i;
            }
            if (prices[maxIndex] < prices[i]){
                maxIndex = i;
                result = Math.max(result, prices[maxIndex]-prices[minIndex]);
            }
        }
        
        return result;
    }
}

No comments:

Post a Comment