1. 程式人生 > >[leetcode] 121. Best Time to Buy and Sell Stock 解題報告

[leetcode] 121. Best Time to Buy and Sell Stock 解題報告

leet 解題報告 情況 lee 動態規劃 turn fit mat etc

動態規劃,註意處理當前最大值小於0的情況

public int maxProfit(int[] prices) {
        if (prices == null || prices.length <= 1) return 0;
        int curMax = 0,result = 0;
        for (int i = 1; i < prices.length; i++) {
            curMax = Math.max(0, curMax + prices[i] - prices[i-1]);
            result = Math.max(curMax,result);
        }
        
return result; }

[leetcode] 121. Best Time to Buy and Sell Stock 解題報告