Medium
068Best Time to Buy and Sell Stock II
Return the maximum profit from as many buy-sell transactions as you want, holding at most one share at a time.
EXAMPLES
Example 1
Input
{
"prices": [
7,
1,
5,
3,
6,
4
]
}
Output
7FUNCTION SHAPE
prices: intArray→intSOLUTION NOTE
Greedy: capture every upward movement. Equivalent to buying every valley and selling every peak.
Reveal reference solution +
pythonREFERENCE
def maxProfit(self, prices: List[int]) -> int:
return sum(max(0, prices[i] - prices[i-1])
for i in range(1, len(prices)))Time
O(n)Space
O(1)