[LC] 121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

思路解析:

给一个数列,先买后卖。所以是用一个min存一个当前找到的最小值,然后price来loop一遍这个,算差值。

 

 

 

public class Solution {
        public int maxProfit(int[] prices) {
            int res = 0, min = Integer.MAX_VALUE;

            for (int i = 0; i < prices.length; i++) {
                min = Math.min(min, prices[i]);
                res = Math.max(res, prices[i]-min);
            }

            return res;
        }
}

 

posted @ 2017-11-11 10:32  mandyliu  阅读(112)  评论(0编辑  收藏  举报