122. Best Time to Buy and Sell Stock II

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

Comparing to first one, this problem can buy and sell several times, first one only do once time. 第一題只能買賣一次, 這題可以買賣多次

/*
    greedy
    
    time complexity: O(n), space complexity:O(1)
*/
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 0; i < prices.length - 1; i++) { // or add  i+1 < prices.length &&  in if statement
            if (prices[i+1] > prices[i]) { // found next price is bigger, add it to profit
                profit += prices[i+1] - prices[i];
            }
        }
        return profit;
    }
}

Last updated