- 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 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:

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

[2, 6, 9, 4, 11]

11

- Related Questions & Answers
- 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
- Maximum profit after buying and selling the stocks in C++
- 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 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
- Program to find maximum profit by selling diminishing-valued colored balls in Python
- Program to find maximum profit we can make after k Buy and Sell 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
- Program to get maximum profit by scheduling jobs in Python
- Find Selling Price from given Profit Percentage and Cost in C++
- Program to find maximum credit we can get by finishing some assignments in python
- Program to find possible number of palindromes we can make by trimming string in Python

Advertisements