[leetcode] Best Time to Buy and Sell Stock

题目:

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

分析:动态规划问题,用一个变量实时保存最大收益,并注意更新查找区域

Java代码:

    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0)
            return 0;
        int min = prices[0], max = prices[0];
        int result = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > max) { // 实时计算并保存最大收益
                max = prices[i];
                if (max - min > result) {
                    result = max - min;
                }
            } else if (prices[i] < min) { // 重新规定查找区域
                min = prices[i];
                max = prices[i];
            }
        }
        return result;
    }

 

posted @ 2015-11-25 18:12  lasclocker  阅读(195)  评论(0编辑  收藏  举报