力扣每日一练(24-1-19)

力扣每日一练(24-1-19)_第1张图片

我的思路:

    def maxProfit(self, prices: List[int]) -> int:
        if not len(prices):
            return 0 

        max_profit = 0
        
        for p in range(len(prices) - 1):
            prices[p] = prices[p + 1] - prices[p]
            prices[p] = max(0, prices[p])
        
        max_profit = sum(prices[:-1])
        return  max_profit

        其实就是把价格数组变成了 :价格变化值数组。

        即从标量(常量)变成了变化量(差异值),把正的变化量相加。

糕手:

Python:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i - 1]:
                max_profit += prices[i] - prices[i - 1]
        return max_profit

C#

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;
}

你可能感兴趣的:(leetcode,算法,职场和发展)