Leetcode 122. The best time to buy and sell stocks II Python implementation

Time:2021-2-6
  • Title Requirements:

Leetcode 122. The best time to buy and sell stocks II Python implementation

  • Thinking:

    • Buy and sell stocks every day, sell the one day before, and buy the one day after
    • Maintain a res to save the total profit
    • If the stock price of the day is higher than that of the previous day, that is, there is a profit, add the profit to res. if there is no profit, add res to 0
    • Return to res
  • Core code:
res = 0
for i in range(1,len(prices)):
    res += max(0, prices[i] - prices[i - 1])
return res
  • Full code:
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        res = 0
        for i in range(1,len(prices)):
            res += max(0, prices[i] - prices[i - 1])
        return res

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]