February 08, 2019

122. Best Time to Buy and Sell Stock II

121. Best Time to Buy and Sell Stock II

Java solution:

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

Python solution:

class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        max_profit = 0
        for i in range(1, len(prices)):
            max_profit = max_profit + max(0, prices[i] - prices[i - 1])
        return max_profit
comments powered by Disqus