122. Best Time to Buy and Sell Stock II
Medium
Problem:
Calculate the maximum profit that can be made through multiple transactions.
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Solution:
This problem originally considered only a single transaction, focusing solely on the low and high points. However, now multiple transactions are possible. The strategy is to sell before a decline and buy before an ascent. Now, we can repeat buying and selling any number of times, as long as it's always in the direction of profit.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# result = 0
# for i in range(len(prices) - 1):
# if prices[i + 1] > prices[i]:
# result += prices[i + 1] - prices[i]
# return result
return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1))
Last updated