Intermediate Level

Implement the maximumProfitMultipleTransactions method that returns the maximum stock profit using multiple valid transactions.

The input contains an array prices and its length size. Each value represents the stock price on that day.

Your task is to return the maximum profit possible when you may complete multiple buy-sell transactions. You cannot hold more than one stock at a time, so you must sell before buying again.

Example 1

Input
prices (int[]) = [7,1,5,3,6,4]
size (int) = 6
Returns (int) 7

Example 2

Input
prices (int[]) = [1,2,3,4,5]
size (int) = 5
Returns (int) 4

Example 3

Input
prices (int[]) = [7,6,4,3,1]
size (int) = 5
Returns (int) 0

For unlimited transactions, every increasing price movement can be counted as profit.

Whenever the price today is higher than the price yesterday, buying yesterday and selling today adds that positive difference to the answer. Adding all such gains gives the same result as choosing the best set of multiple transactions.

Ignore decreasing or equal movements because they do not create profit.

Pseudocode:

function maximumProfitMultipleTransactions(prices, size):
    totalProfit = 0
    for i from 1 to size - 1:
        if prices[i] > prices[i - 1]:
            totalProfit = totalProfit + prices[i] - prices[i - 1]
    return totalProfit
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.