Skip to content

Latest commit

 

History

History
22 lines (20 loc) · 548 Bytes

122. Best Time to Buy and Sell Stock II.md

File metadata and controls

22 lines (20 loc) · 548 Bytes

Solution1

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

note

  • Time O(n) space O(1)
  • The idea is very simple. Add up all difference between prices[i + 1] and prices[i] if prices[i + 1] > prices[i].