- Related Questions & Answers
- Best Time to Buy and Sell Stock II in Python
- Best Time to Buy and Sell Stock III in Python
- Best Time to Buy and Sell Stock IV in C++
- Best Time to Buy and Sell Stock with Cooldown in C++
- Program to find maximum profit we can make after k Buy and Sell in python
- What is the best site to invest money in stock market?
- Write the difference between stock market and stock exchange.
- Differentiate stock and bonds.
- Write the difference between large cap stock and small cap stock.
- Which is the best site to buy back-covers, flip-covers, and screen guards for mobile phones?
- Find the minimum and maximum amount to buy all N candies in Python
- How to sell your Bitcoin?
- Best way to store date/time in MongoDB?
- Compare stock market and commodity market.
- Compare asset purchase and stock purchase.

- 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 an array A, here A[i] is indicating the price of a given stock on day i. We have to find the maximum profit. We can complete at most one transaction. (Transaction means to buy and sell stocks). But we have to keep in mind that we may not engage in multiple transactions at the same time. So we have to sell the stock before buying the new one.

Suppose the array is like A = [7, 1, 5, 3, 6, 4], then the result will be 5. As we can see, if we buy on day 2 (index 1), then it will take 1 as a buying price. Then if we sell on day 5, the profit will be 6 – 1 = 5.

To solve this, follow these steps −

- create two arrays leftMin, and rightMax of size same as A, and fill them with 0s
- leftMin[0] = A[0]
- for i in range 1 to length of A – 1, leftMin[i] = minimum of leftMin[i – 1] and A[i]
- rightMax[n-1] = A[n – 1]
- for i in range length of A – 1 down to 1, rightMax[i] = maximum of rightMax[i + 1] and A[i]
- set answer := 0
- for i in range 0 to length of A – 1, answer := max of answer and rightMax[i + 1] – leftMin[i]
- return answer

Let us see the implementation to get better understanding

class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 leftMin,rightMax = [0 for i in range(len(prices))],[0 for i in range(len(prices))] leftMin[0] = prices[0] for i in range(1,len(prices)): leftMin[i] = min(leftMin[i-1],prices[i]) #print(leftMin) rightMax[-1]= prices[-1] for i in range(len(prices)-2,-1,-1): rightMax[i] = max(rightMax[i+1],prices[i]) #print(rightMax) ans = 0 for i in range(len(prices)-1): ans = max(ans,rightMax[i+1]-leftMin[i]) return ans ob1 = Solution() print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))

prices = [7,2,5,8,6,3,1,4,5,4,7]

6

Advertisements