Program to find the maximum profit we can get by buying on stock market multiple times in Python

Suppose we have a list of prices representing the stock prices of a company in chronological sequence, we have to find the maximum profit we could have made from buying and selling that stock any number of times. We have to keep in mind that we must buy before we can sell it.

So, if the input is like prices = [10, 50, 30, 40, 60], then the output will be 70, as we can buy at 10, sell at 50, buy at 30, and sell at 60.

Algorithm

To solve this, we will follow these steps:

  • prev_price := infinity
  • profit := 0
  • for each p in prices, do
    • if p > prev_price, then
      • profit := profit + p - prev_price
    • prev_price := p
  • return profit

Implementation

Let us see the following implementation to get better understanding:

class Solution:
    def solve(self, prices):
        prev_price = float("inf")
        profit = 0
        for p in prices:
            if p > prev_price:
                profit += p - prev_price
            prev_price = p
        return profit

ob = Solution()
print(ob.solve([10, 50, 30, 40, 60]))
70

How It Works

The algorithm works by capturing every profitable price increase. When the current price is higher than the previous price, we add the difference to our total profit. This approach automatically handles multiple buy-sell transactions to maximize profit.

Alternative Approach

We can also solve this using a simpler approach by directly comparing consecutive prices:

def max_profit(prices):
    profit = 0
    for i in range(1, len(prices)):
        if prices[i] > prices[i-1]:
            profit += prices[i] - prices[i-1]
    return profit

prices = [10, 50, 30, 40, 60]
print(max_profit(prices))
70

Conclusion

The key insight is to capture every profitable price increase by buying before each upward trend and selling at peaks. Both approaches achieve O(n) time complexity with maximum profit calculation.

Updated on: 2026-03-25T10:41:04+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements