Skip to main content

Buy and Sell Stock

MediumPremium

Maximize Stock Trading Profit. You are given a sequence of stock prices representing the value of a particular stock on consecutive days. You can complete as many transactions as you like with the following constraints:

  1. You must buy before you sell.
  2. You cannot buy on one day and sell on the same day (buying and selling in the same day counts as nothing).

Maximize your profit given these conditions.

For example, consider the following stock prices over a week: 1, 2, 3, 4, 5. If you buy on day 1 and sell on day 5, your profit will be 4 (buy at 1 and sell at 5).

Examples

stock_prices = [7, 1, 5, 3, 6, 4] output: 7 (Buy on day 2 at 1, sell on day 3 at 5, buy on day 4 at 3, and sell on day 5 at 6) stock_prices = [1, 2, 3, 4, 5] output: 4 (Buy on day 1 at 1 and sell on day 5 at 5) stock_prices = [7, 6, 4, 3, 1] output: 0 (No transaction is done, i.e., max profit = 0) stock_prices = [1, 10, 2, 3] output: 9 (Buy on day 1 at 1 and sell on day 2 at 10)