Back to the 100
Problem 068Dynamic Programming
Medium

Best Time to Buy and Sell Stock II

068

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
7

FUNCTION SHAPE

prices: intArrayint
SOLUTION 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)))
TimeO(n)
SpaceO(1)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.