Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Best Time to Buy and Sell Stock II

Easy
greedyarray

Given daily prices, you may buy and sell as many times as you like (holding at most one share at a time; selling and re-buying the same day is allowed). Return the maximum total profit.

Input: one line of space-separated prices. Output: the maximum profit.

Example 1
Input:
7 1 5 3 6 4
Output:
7

Buy 1 → sell 5 (+4), buy 3 → sell 6 (+3).

Example 2
Input:
1 2 3 4 5
Output:
4

One long hold — or every daily rise; same total.

Example 3
Input:
7 6 4 3 1
Output:
0

Constraints

  • 1 ≤ prices.length ≤ 3·10^4
  • 0 ≤ prices[i] ≤ 10^4
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.