贪心策略---买卖股票最大的收益

买卖股票最大的收益

121. Best Time to Buy and Sell Stock (Easy)

题目描述:

  一次股票交易包含买入和卖出,只进行一次交易,求最大的收益。

思路分析:

  只要记录下前面的最小价格,将这个价格作为买入价格,然后将当前价格作为售出价格,查看当前收益是不是最大收益。

代码:

class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<=1)
            return 0;
        int min=prices[0];
        int max=Integer.MIN_VALUE;
        for(int i=1;i<prices.length;i++){
            if(min>prices[i])
                min=prices[i];
            max=Math.max(max,prices[i]-min);
        }
        return max;
    }
}
posted @ 2019-06-29 10:19  yjxyy  阅读(329)  评论(0编辑  收藏  举报