- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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]))

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

6

- Related Questions & Answers
- Program to find the maximum profit we can get by buying on stock market multiple times in Python
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Program to find maximum profit we can get by buying and selling stocks with a fee in Python?
- Program to find maximum profit we can make by holding and selling profit in Python
- Program to get maximum profit by scheduling jobs in Python
- Program to find maximum credit we can get by finishing some assignments in python
- Program to find maximum profit after buying and selling stocks at most two times in python
- Maximum profit by buying and selling a share at most twice
- Program to find maximum profit we can make after k Buy and Sell in python
- Maximum profit after buying and selling the stocks in C++
- Program to find maximum amount we can get by taking different items within the capacity in Python
- Program to find maximum price we can get by holding items into a bag in Python
- Program to find maximum profit by selling diminishing-valued colored balls in Python
- Program to find maximum number of coins we can get using Python
- Program to find maximum score we can get in jump game in Python

Advertisements