- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# Program to find maximum profit we can make by buying and selling stocks in Python?

Suppose we have a list of stock prices of a company in chronological order, we have to find the maximum profit we could have made from buying and selling the stock. We must buy before selling, and we must wait one day after selling the stock before buying again.

So, if the input is like prices = [2, 6, 9, 4, 11], then the output will be 11, as we can buy at 2, then sell at 6, wait for a day, then buy at 4 and then sell at 11.

To solve this, we will follow these steps:

s := 0

b := -infinity

for i in range 0 to size of prices, do

temp := b

b := maximum of b and (s - prices[i])

if i is non-zero, then

s := maximum of s and (temp + prices[i - 1])

return maximum of s and (b + last element of prices)

Let us see the following implementation to get better understanding:

## Example

class Solution: def solve(self, prices): s = 0 b = float("-inf") for i in range(len(prices)): temp = b b = max(b, s - prices[i]) if i: s = max(s, temp + prices[i - 1]) return max(s, b + prices[-1]) ob = Solution() prices = [2, 6, 9, 4, 11] print(ob.solve(prices))

## Input

[2, 6, 9, 4, 11]

## Output

11

- Related Articles
- 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 find maximum profit after buying and selling stocks at most two times in python
- Maximum profit after buying and selling the stocks in C++
- Program to find the maximum profit we can get by buying on stock market once in Python
- Program to find the maximum profit we can get by buying on stock market multiple 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
- C++ program to find maximum profit we can make by making hamburger and chicken burgers
- Program to find maximum profit by selling diminishing-valued colored balls in Python
- Program to find maximum profit after cutting rods and selling same length rods in Python
- Program to find maximum number of people we can make happy in Python
- C++ Program to find out the maximum amount of profit that can be achieved from selling wheat
- Program to get maximum profit by scheduling jobs in Python
- Program to find maximum credit we can get by finishing some assignments in python