ExamAdda Logo

Best Time to Buy and Sell Stock II

Easy

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

However, you may not hold more than one share of the stock at a time. You must sell the stock before buying again.

Return the maximum profit you can achieve.

Example 1

Input

6
7 1 5 3 6 4

Output

7

Explanation

Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 4.

Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 3.

Total profit = 4 + 3 = 7.

Example 2

Input

5
1 2 3 4 5

Output

4

Explanation

Buy on day 1 and sell on day 5.

The maximum profit is 5 − 1 = 4.

Constraints

1 ≤ prices.length ≤ 3 × 10⁴
0 ≤ prices[i] ≤ 10⁴

Hints:

Hint 1

Whenever today's price is higher than yesterday's price, that increase contributes to the maximum profit.

Hint 2

Instead of finding one large transaction, accumulate the profit from every increasing price sequence.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 4, 2026

Last updated

Aug 4, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output