LeetCode - 122. Best Time to Buy and Sell Stock II

相比於上一道題目Best Time to Buy and Sell Stock,這道題目可以交易多次,那麼在從前向後掃描數組的過程中,只要後面一天的股票價格高於當今的股票價格,就進行股票的交易,相當於是使用了貪心的思想,代碼如下:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) return 0;      // corner case
        
        int result = 0;
        for(int i = 0; i < prices.length - 1; i++){
            if(prices[i + 1] > prices[i]){
                result += prices[i + 1] - prices[i];
            }
        }
        
        return result;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章