LeetCode - 121. Best Time to Buy and Sell Stock

链接

121. Best Time to Buy and Sell Stock

题意

买股票,
注意只能买卖一次。

思路

用min记录已遍历的最小值(相当于买入),同时用当前值(相当于卖出)减去min,不断更新最大利润即可。

代码

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0) return 0;
        int res = 0;
        int min = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] < min) min = prices[i];
            if (prices[i] - min > res) res = prices[i] - min;
        }
        return res;
    }
}
posted @ 2017-06-21 18:30  zyoung  阅读(141)  评论(0编辑  收藏  举报