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

PythonServer Side ProgrammingProgramming

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 only once. We have to keep in mind that we must buy before we can sell it.

So, if the input is like prices = [10, 12, 9, 6, 8, 12], then the output will be 6, as we can buy at 6 and sell at 12.

To solve this, we will follow these steps −

  • max_profit := 0
  • min_stock := infinity
  • for each price in prices, do
    • max_profit := maximum of max_profit and (price - min_stock)
    • min_stock := minimum of min_stock and price
  • return max_profit

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, prices):
      max_profit = 0
      min_stock = float('inf')
      for price in prices:
         max_profit = max(max_profit, price - min_stock)
         min_stock = min(min_stock, price)
      return max_profit
ob = Solution()
print(ob.solve([10, 12, 9, 6, 8, 12]))

Input

[10, 12, 9, 6, 8, 12]

Output

6
raja
Published on 05-Oct-2020 12:03:24
Advertisements