122. Best Time to Buy and Sell Stock II
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii
Python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
total_profit = 0
profit = 0
b, s = 0, 0
while s < len(prices):
if prices[s] > prices[b]:
profit = max(profit, prices[s] - prices[b])
b = s
else:
total_profit += profit
profit = 0
b = s
s += 1
return total_profit
Go
func maxProfit(prices []int) int {
total_profit := 0
profit := 0
b := 0
s := 0
for s < len(prices) {
if prices[s] > prices[b] {
if prices[s] - prices[b] > profit {
profit = prices[s] - prices[b]
b = s
}
} else {
total_profit += profit
profit = 0
b = s
s += 1
}
}
return total_profit
}