- 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
Best Time to Buy and Sell Stock III in Python
Suppose we have an array for which the ith element is representing the price of a given stock on day i. We have to devise an algorithm to find the maximum profit. We can complete at most two transactions. So if the given prices are [3,3,5,0,1,3,1,4], then the result will be 6, as we will buy on day 4 (price 0), then sell on day 6, (price 3), so profit is 3 – 0 = 3. Now but on day 7 (price 1), and sell on day 8 (price 4) so profit is 4 – 1 = 3.
To solve this, we will follow these steps −
n := size of s, m := size of t. Update s and t by concatenating blank spaces before them
Make one matrix of size (n + 1) x (m + 1)
set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1
for i in range 1 to n
for j in range 1 to m
if s[i] = t[j], then
dp[i, j] := dp[i – 1, j – 1]
dp[i, j] := dp[i, j] + dp[i – 1, j]
return dp[n, m]
Example
Let us see the following implementation to get better understanding −
class Solution(object): def maxProfit(self, p): if not p: return 0 n = len(p) dp = [0 for i in range(n)] ans = 0 xmin = p[0] for i in range(1,n): xmin = min(xmin,p[i]) dp[i] = max(dp[i],p[i]-xmin) ans = max(ans,dp[i]) xmax = [0 for i in range(n)] xmax[-1] =p[-1] tempp = 0 for i in range(n-2,-1,-1): xmax[i] = max(xmax[i+1],p[i]) xmin = [p[-1],n] for i in range(n-2,-1,-1): tempp = max(tempp,xmax[i+1]-p[i+1]) ans = max(ans,dp[i]+tempp) return ans ob = Solution() print(ob.maxProfit([3,3,5,0,1,3,1,4]))
Input
[3,3,5,0,1,3,1,4]
Output
6
- Related Articles
- Best Time to Buy and Sell Stock in Python
- Best Time to Buy and Sell Stock II 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?
- Which is the best site to buy back-covers, flip-covers, and screen guards for mobile phones?
- Best way to store date/time in MongoDB?
- Find the minimum and maximum amount to buy all N candies in Python
- Write the difference between stock market and stock exchange.
- I buy a T.V. for $Rs. 10,000$ and sell it at a profit of $20 %$. How much money do I get for it?
- What is the best time to visit Tirupathi?
- Differentiate stock and bonds.
- Write the difference between large cap stock and small cap stock.
- What is stock and scion?
