Back to DSA sheet

Best Time to Buy And Sell Stock II

MediumArrays

You may buy and sell a stock as many times as you like (but hold at most one share at a time). Maximize the total profit.

Input format (stdin): the first line has n. The second line has n prices. Output the maximum profit.

Examples
Input: 6 7 1 5 3 6 4
Output: 7
Buy at 1 sell at 5 (+4), buy at 3 sell at 6 (+3).
Input: 5 1 2 3 4 5
Output: 4
Buy day 1, sell day 5.
Constraints
  • 1 <= n <= 3*10^4
  • 0 <= prices[i] <= 10^4
Sheets
NeetCode 250
best-time-to-buy-and-sell-stock-ii.cpp3 sample tests
Loading editor
Test results

Run the sample tests to check your solution against expected output.

Custom input (stdin)
Output

Run your code to see its output.