Loading problem...
You are provided with an integer array representing the daily price of an asset over a period of time, where each element corresponds to the price on a specific day.
Your goal is to determine the maximum total profit that can be achieved through multiple buy and sell transactions. The trading rules are as follows:
Single Holding Constraint: At any given moment, you can possess at most one unit of the asset. This means you must sell your current holding before making another purchase.
Unlimited Transactions: There is no restriction on the number of transactions you can execute. You may buy and sell as many times as you wish throughout the period.
Same-Day Trading: Remarkably, you are permitted to sell and then immediately buy again on the same day if you choose. This allows for maximum flexibility in capturing every profitable opportunity.
No Transaction Fees: Each transaction is cost-free, so you only need to consider the price differences.
Your task is to compute the maximum cumulative profit achievable by strategically timing your transactions. If no profitable trades are possible (for instance, when prices consistently decline), return 0 as the maximum profit.
prices = [7,1,5,3,6,4]7Purchase on day 2 at price 1 and sell on day 3 at price 5, earning a profit of 4. Subsequently, buy on day 4 at price 3 and sell on day 5 at price 6, gaining an additional profit of 3. The combined profit equals 4 + 3 = 7.
prices = [1,2,3,4,5]4With prices steadily increasing each day, you can either: (a) buy on day 1 and hold until day 5 for a profit of 5 - 1 = 4, or (b) make four consecutive trades by buying and selling each day for gains of (2-1) + (3-2) + (4-3) + (5-4) = 4. Both strategies yield the same maximum profit of 4.
prices = [7,6,4,3,1]0Since the price drops every day, there are no opportunities to make a profit through any transaction. The optimal strategy is to abstain from trading entirely, resulting in a maximum profit of 0.
Constraints