Understood or nott? am waiting in the comment section ;) . Check me out at Instagram: instagram.com/striver_79/ . If you appreciate the channel's work, you can join the family: bit.ly/joinFamily
Understood!!!. Great work. Thanks for such a great channel. A few days back, I found this masterpiece channel named @take U forward. Now I am just following your SDE-PROBLEM sheet every day, and coding is like a daily routine for me.
I have an honest confession to make. Before I found your channel, I didn't think product companies were for me. Tbh, I never had a clear picture as of how I should prepare for them . I wasn't into competitive programming at all. Yet, I am ambitious and want to do something good. It won't be so wrong to say you changed my life. If you see this comment, I want you to know what an amazing work you're doing. I wish I had found your channel in 1st year. Thank you so much! Lots of love and gratitude :)
Brute force approach in C++ {T(n) = O(n^2)} | if anybody is interested to know: Note: If you run submit this colution on Leetcode, the time exceed error comes, so need to optimize and submit. int n = prices.size(); if(1 == n) return 0; int max_profit = 0; for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { max_profit = max(max_profit, prices[j] - prices[i]); } } return max_profit;
Hi, First, he buys the stock at 1 and sells it at 5. Then again he buys at 3 and sells it again at 6, so the profit would be 5-1=4 and 6-3=3, a total of 7 right. but you got 5. I don't know is this a subversion of this problem, but heard this problem.
I think there is a flaw in the logic. Correct me if I'm wrong. For the scenario (20,50,10,30), the minimum would be taken as 10 and max profit will be calculated as 20 based on that. But a manual inspection shows that we shouldn't have switched the minimum from 20 to 10. The maximum profit is for buy at 20 and sell at 50. Making the max profit as 30.
@@kaushiktlk consider this as buying in real life. On any current day, you can only compare with previous days and pick minimum. We cannot see in future if there will be minimum which is lesser than our current minimum or not. That's not possible. We have to pick minimum from the elements we have visited so far. And for this question, you can only buy once and sell once.
@@Polly10189 if we should consider as a real life scenario where we cannot see into the future then we won't be able to know the real maximum at which we should sell. There is some inconsistency.
Yes, that's absolutely correct! For those not familiar, Kadane's algorithm is a dynamic programming algorithm used to solve the maximum subarray problem, which is the task of finding the contiguous subarray with the largest sum in a one-dimensional array. The solution to the "Best Time to Buy and Sell Stock II" problem, where you can make as many transactions as you like, is somewhat similar to the maximum subarray problem. However, there's a slight but significant difference: In the stock problem, we want to find the maximum sum of all positive differences (i.e., all increases in price), regardless of whether they're contiguous or not, whereas in the maximum subarray problem, we're looking for the maximum sum of a contiguous subarray. When you calculate the difference array and apply Kadane's algorithm, you're finding the maximum sum of a contiguous subsequence of the difference array. This might not give you the correct answer for the stock problem because you're allowed to buy and sell on non-contiguous days as well. Therefore, the correct approach to the "Best Time to Buy and Sell Stock II" problem is to add up all positive differences, without requiring them to be contiguous. This is simpler than applying Kadane's algorithm, and guarantees that you get the correct answer.
TC : O(N) and SC : O(1) .. c++ code class Solution { public: int maxProfit(vector& prices) { int profit=0; int mini=INT_MAX; int ans=INT_MIN; int n=prices.size(); for(int i=0;itemp){ mini=temp; } profit=prices[i]-mini; if(profit>ans){ ans=profit; } } return ans; } };
What are the most common Stock Buy Pattern?Variation questions? One is to find the max profit, another is to find total profit. Can you people suggest more??
Nice explaination,We need mentors like you to understand these concept so easily.I had started preparing after a lot of failure might this time i got success ,I am trying to following all the startegy which you had shared to get into a big company.
Hello you are doing amazing job. I have one question what if in question instead of one transaction there are unlimited transactions are allowed ? Can you please give me a hint or brief idea ?
Great explanation brother. I implemented the solution using dictionaries (Python) and my logic is also working great, but there is an error in my code which I am unable to debug, could you please guide me? Thanks in advance EDIT: MY CODE IS FIXED BUT TAKES 5008ms TO RUN, IS IT GOOD?
Initially, I solve from the back of the array and got WA on some test cases then tried front View and yeh got it👍👍 Point here I understood after doing this kind of problems is that 👉NEVER GO TOO COMPLICATED 👈 😅😅
Actually I also did from the rear end of array . That also works . See.. //code begins here int n=prices.size(); int maxp=prices[n-1]; int ans=0; for(int i=n-2;i>=0;i--) { ans=max(maxp-prices[i],ans); maxp=max(maxp,prices[i]); }
@takeuforward if I submit this code with O(n) complexity on leetcode, it says slower than 94% of Cpp solutions class Solution { public: int maxProfit(vector& prices) { int mini = INT_MAX; int profit = 0; for(int i = 0; i mini){ profit = max(profit, prices[i] - mini); } else{ mini = min(mini,prices[i]); } } return profit; } }; When I look for other's optimized solutions they also have O(n) solution which is 8x times less time-consuming.... Please clarify it??
// A cleaner Java version class Solution { public int maxProfit(int[] prices) { int min = Integer.MAX_VALUE; int profit = 0; for (int p : prices) { min = Math.min(p, min); profit = Math.max( profit, p - min); } return profit; } }
Bhaiya can you please discuss the soln, for what happens if we can (sell and purchase) each transaction atmost k times and you must sell the stock before you buy the next stock
If the problem is extended to allow up to k transactions, the complexity increases, but it can still be solved using dynamic programming. You'll need a two-dimensional array `profit[t][d]`, where `t` is the transaction index (from 0 to k) and `d` is the day index (from 0 to the number of days - 1). `profit[t][d]` represents the maximum profit we can get by making at most `t` transactions up to day `d`. You can initialize `profit[t][0]` to 0 for all `t` (since you can't make a profit on the first day), and `profit[0][d]` to 0 for all `d` (since you can't make a profit with 0 transactions). Then, you'll iterate over `t` and `d` to fill in the rest of the `profit` array. For each pair `(t, d)`, you have two options: 1. Don't make a transaction on day `d`. In this case, the profit is the same as it was on the previous day, i.e., `profit[t][d - 1]`. 2. Sell a stock on day `d`. In this case, you need to find the day to buy the stock that maximizes the profit. Let's call this day `d'`. You buy on day `d'` and sell on day `d`, and you also get the profit from making `t - 1` transactions up to day `d' - 1`. This gives you a profit of `prices[d] - prices[d'] + profit[t - 1][d' - 1]`. You'll take the maximum over all possible `d'` (from 0 to `d - 1`). So, you'll fill in `profit[t][d]` as `max(profit[t][d - 1], prices[d] - prices[d'] + profit[t - 1][d' - 1] for all d' in [0, d - 1])`. Finally, the maximum profit you can get is `profit[k][n - 1]`, where `n` is the number of days. This solution has a time complexity of O(k*n^2) because for each pair `(t, d)`, it iterates over `[0, d - 1]` to find the best day `d'` to buy the stock. The time complexity can be reduced to O(k*n) by keeping track of the maximum value of `prices[d'] - profit[t - 1][d' - 1]` for all `d'` in `[0, d - 1]`, and updating it for each `d`. This value represents the maximum profit you can get by ending your `t - 1`th transaction on or before day `d' - 1` and starting your `t`th transaction on day `d'`. Here is the pseudo code for this: ```python function maxProfit(prices, k): n = len(prices) if k > n / 2: return quickSolve(prices) # quickSolve() is the function for unlimited transactions profit = [[0]*n for _ in range(k+1)] for t in range(1, k+1): maxDiff = -prices[0] for d in range(1, n): profit[t][d] = max(profit[t][d - 1], prices[d] + maxDiff) maxDiff = max(maxDiff, profit[t - 1][d - 1] - prices[d]) return profit[k][n - 1] ``` In this code, `maxDiff` is the maximum value of `profit[t - 1][d' - 1] - prices[d']` for all `d'` in `[0, d - 1]`. We update `maxDiff` for each `d` to ensure that it always represents the best day `d'` to buy the stock for the current transaction and day.
To print all the transaction options for maximum profit, we need to slightly modify our approach. Along with tracking the maximum profit, we need to also track the decisions we made at each point. After computing the maximum profit table, you can backtrack from `profit[k][n-1]` to find the transactions. If `profit[t][d]` is not equal to `profit[t][d - 1]`, it means we made a transaction on day `d`. We can then find the day `d'` we bought the stock by searching for `d'` such that `prices[d] - prices[d'] + profit[t - 1][d' - 1]` equals `profit[t][d]`. This is essentially the inverse of the computation we did to fill in the `profit` array. This approach can be quite complex and time-consuming because for each transaction, you have to search for the day you bought the stock. An alternative approach is to store the decisions directly in another array during the dynamic programming step. Here is a rough pseudo code for the entire approach: ```python function maxProfit(prices, k): n = len(prices) if k > n / 2: return quickSolve(prices) # quickSolve() is the function for unlimited transactions profit = [[0]*n for _ in range(k+1)] decision = [[0]*n for _ in range(k+1)] # new decision array for t in range(1, k+1): maxDiff = -prices[0] for d in range(1, n): if prices[d] + maxDiff > profit[t][d - 1]: profit[t][d] = prices[d] + maxDiff decision[t][d] = d # store the decision of making a transaction on day d else: profit[t][d] = profit[t][d - 1] maxDiff = max(maxDiff, profit[t - 1][d - 1] - prices[d]) # backtracking to find the transactions transactions = [] d = n - 1 for t in range(k, 0, -1): if decision[t][d] != 0: # if we made a transaction on day d buy_day = decision[t][d] sell_day = d transactions.append((buy_day, sell_day)) # add the transaction to the list d = buy_day - 1 # move to the day before we bought the stock return profit[k][n - 1], transactions[::-1] # reverse the transactions list to get them in chronological order ``` This code will return the maximum profit as well as the list of transactions. Each transaction is a pair `(buy_day, sell_day)` indicating the day you bought the stock and the day you sold it. Please note that this pseudo code is simplified and assumes perfect inputs, so you should add your own error checking and edge case handling where necessary.
But one question, this is solved by u or some one ..., I ask one thing all the optimised solutions thought in your mind or took from some where, Becoz I want to analyze my IQ, I didnt get any optimal solutions in my mind ,am I able to crack amazon
Understood or nott? am waiting in the comment section ;)
.
Check me out at Instagram: instagram.com/striver_79/
.
If you appreciate the channel's work, you can join the family: bit.ly/joinFamily
Yah ! understood
speed is perfect as this series is focused on coming placements..understood..
understood
Understood bro! Thank you :)
Understood!!!. Great work. Thanks for such a great channel. A few days back, I found this masterpiece channel named @take U forward. Now I am just following your SDE-PROBLEM sheet every day, and coding is like a daily routine for me.
I have an honest confession to make. Before I found your channel, I didn't think product companies were for me. Tbh, I never had a clear picture as of how I should prepare for them . I wasn't into competitive programming at all. Yet, I am ambitious and want to do something good. It won't be so wrong to say you changed my life. If you see this comment, I want you to know what an amazing work you're doing. I wish I had found your channel in 1st year. Thank you so much! Lots of love and gratitude :)
Welcome aboard as a subscriber, haha ! Thanks for the wonderful comment !
Don’t worry , it’s never too late, I’m already in product based company, also having 6 + yrs of experiences, still learning 😇😇
You got placed?
@@Tarun-Mehta in which company ?
Brute force approach in C++ {T(n) = O(n^2)} | if anybody is interested to know:
Note:
If you run submit this colution on Leetcode, the time exceed error comes, so need to optimize and submit.
int n = prices.size();
if(1 == n) return 0;
int max_profit = 0;
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
max_profit = max(max_profit, prices[j] - prices[i]);
}
}
return max_profit;
at 2:45, we could also have traversed the array from the right side and keep track of maximum in right for every i.
Yes similar to the minimum approach, both works fine !
This was great. Also, this question has various variations of difficulty. If you could compile all the questions in 1 video then that would be great.
Python solution (Accepted on Leetcode):
Time Complexity: O(n)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_elem = prices[0]
max_profit = 0
if len(prices) == 1:
return 0
else:
for index,item in enumerate(prices):
if index > 0:
diff = item - min_elem
if diff < 0:
min_elem = item
continue
else:
max_profit = max(max_profit,diff)
return max_profit
Hi,
First, he buys the stock at 1 and sells it at 5. Then again he buys at 3 and sells it again at 6, so the profit would be 5-1=4 and 6-3=3, a total of 7 right. but you got 5.
I don't know is this a subversion of this problem, but heard this problem.
Very helpful series. KEEP UP THE GOOD WORK!!
Please upload the rest of the problems as well it would be really helpful.
I think there is a flaw in the logic. Correct me if I'm wrong. For the scenario (20,50,10,30), the minimum would be taken as 10 and max profit will be calculated as 20 based on that. But a manual inspection shows that we shouldn't have switched the minimum from 20 to 10. The maximum profit is for buy at 20 and sell at 50. Making the max profit as 30.
You cannot skip the day.
@Polly10189, can you please elaborate?
@@kaushiktlk consider this as buying in real life. On any current day, you can only compare with previous days and pick minimum. We cannot see in future if there will be minimum which is lesser than our current minimum or not. That's not possible. We have to pick minimum from the elements we have visited so far. And for this question, you can only buy once and sell once.
@@Polly10189 if we should consider as a real life scenario where we cannot see into the future then we won't be able to know the real maximum at which we should sell. There is some inconsistency.
This is in a way an application of Kadane's algorithm. First get the difference between current - previous. Then apply Kadane's algo on the result.
Yes, that's absolutely correct!
For those not familiar, Kadane's algorithm is a dynamic programming algorithm used to solve the maximum subarray problem, which is the task of finding the contiguous subarray with the largest sum in a one-dimensional array. The solution to the "Best Time to Buy and Sell Stock II" problem, where you can make as many transactions as you like, is somewhat similar to the maximum subarray problem.
However, there's a slight but significant difference: In the stock problem, we want to find the maximum sum of all positive differences (i.e., all increases in price), regardless of whether they're contiguous or not, whereas in the maximum subarray problem, we're looking for the maximum sum of a contiguous subarray.
When you calculate the difference array and apply Kadane's algorithm, you're finding the maximum sum of a contiguous subsequence of the difference array. This might not give you the correct answer for the stock problem because you're allowed to buy and sell on non-contiguous days as well.
Therefore, the correct approach to the "Best Time to Buy and Sell Stock II" problem is to add up all positive differences, without requiring them to be contiguous. This is simpler than applying Kadane's algorithm, and guarantees that you get the correct answer.
TC : O(N) and SC : O(1) .. c++ code
class Solution {
public:
int maxProfit(vector& prices) {
int profit=0;
int mini=INT_MAX;
int ans=INT_MIN;
int n=prices.size();
for(int i=0;itemp){
mini=temp;
}
profit=prices[i]-mini;
if(profit>ans){
ans=profit;
}
}
return ans;
}
};
What are the most common Stock Buy Pattern?Variation questions?
One is to find the max profit, another is to find total profit. Can you people suggest more??
ua-cam.com/video/SHIv9jNOWLE/v-deo.html
Refer pepcoding dynamic programming level 1 playlist it has 6 questions of buy and sell stock
i think max ans for the explaned array should be 7, buy at 1 sell at 5 profit 4 now buy at 3 and sell at 6 profit 3, total profit 7
This is a single transaction only problem.
Please make a video on "n stocks buying and selling"
Striver bro 😂😂kahi aisa na ho ki inn videos ki popularity dekh ke faang nye concepts se interview lene lge. ie system design, db etc se😅😅
haha
small correction in required,
because I can buy at 1 and sell for 5, then buy for 3 and sell for 6,
then my profit is 7 which is max profit.
Nice explaination,We need mentors like you to understand these concept so easily.I had started preparing after a lot of failure might this time i got success ,I am trying to following all the startegy which you had shared to get into a big company.
Me and my boiss after solving this question...
Harshhod mehhta😎
More clean code
class Solution {
public int maxProfit(int[] prices) {
int max=0;
int min = prices[0];
for(int i=1;i
I got this question in OYO campus placement test
Optimal Approach makes so much sense.
Hello you are doing amazing job. I have one question what if in question instead of one transaction there are unlimited transactions are allowed ? Can you please give me a hint or brief idea ?
Great explanation brother. I implemented the solution using dictionaries (Python) and my logic is also working great, but there is an error in my code which I am unable to debug, could you please guide me?
Thanks in advance
EDIT: MY CODE IS FIXED BUT TAKES 5008ms TO RUN, IS IT GOOD?
no
Initially, I solve from the back of the array and got WA on some test cases then tried front View and yeh got it👍👍
Point here I understood after doing this kind of problems is that 👉NEVER GO TOO COMPLICATED 👈 😅😅
Actually I also did from the rear end of array . That also works . See..
//code begins here
int n=prices.size();
int maxp=prices[n-1];
int ans=0;
for(int i=n-2;i>=0;i--)
{
ans=max(maxp-prices[i],ans);
maxp=max(maxp,prices[i]);
}
return ans;
@takeuforward if I submit this code with O(n) complexity on leetcode, it says slower than 94% of Cpp solutions
class Solution {
public:
int maxProfit(vector& prices) {
int mini = INT_MAX;
int profit = 0;
for(int i = 0; i mini){
profit = max(profit, prices[i] - mini);
}
else{
mini = min(mini,prices[i]);
}
}
return profit;
}
};
When I look for other's optimized solutions they also have O(n) solution which is 8x times less time-consuming....
Please clarify it??
Lot of factors involved, like server speed and other factors like if else etc. Minute factors, ignore and focus on logic
@@takeUforward Thanks
This is something like kadane's algorithms right?
Is the second approach a DP aaproach? like Kadanes Algo
UNDERSTOOD...!
Thanks striver for the video... :)
i must say this series is super helpful and I'm loving your explanation , please upload faster 4-5 que a day ...so that we can maintain our pace :-)
Not possible bro.. am a working guy !
@@takeUforward bhaiya it will 180 days like this please just make it 2-3 😶
TC O(N^2)
BRUTEFORCE :
#include
using namespace std;
int main()
{
//int arr[]= {7,6,4,3,1};
int n=sizeof(arr)/sizeof(arr[0]);
int maxi=-23443322;
if(n==1)
{
cout
int maxProfit(vector& arr) {
int maxi=-23443322;
for(int i=0;i
One of the best lecture which I saw in Utube
Y minprice is initialize with INT_MAX;
Understand very well🤗
Thank you! Cheers!
Your explanation is really good.
and differnt approach to do same problem, makes it awsm
Thanks bro !
// A cleaner Java version
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int profit = 0;
for (int p : prices) {
min = Math.min(p, min);
profit = Math.max( profit, p - min);
}
return profit;
}
}
Do we update the minimum if we get some mimimum value?
Yes..
What if the input is 7, 4, 6, 1, 2?
For 4 the profit will be 2 but if we change the minimum to 1 again then the profit will be 1.
@@vaibhavchawla7353 buy at 4 sell at 6, that will the max profit.. next time when the minimal is 1, you get 2, but that profit will be 1.
@@takeUforward ok ok got it. 👌👍
Thank you sir
if you are solving this then do also solve the other 4 versions of the problem
Such an elegant solution!
Nice question.. I understood.
Quite an easy fix one ....Keep going bhai...grt work ....👌👌👌
Thank you so much 😀
Ye toh jayada hi aasan tha yaar..
Understood❣️❣️
Thank you! Cheers!
The bruteforce solution you taught here will not work. Check gfg's bruteforce solution for this.
Can't we allow multiple buying and selling
amazing describe sir thank you
why min value is not changing i dont understand
I have a doubt Bhaiya, why didn't you use if-else in CPP soln, like you did in your Java soln?
An approach can be written in multiple ways,
Understood. ❤️ .. you are the best. 💯💯
understood it very well...thanks bhaiya
Keep watching
@@takeUforward definately
129 likes 0 dislikes that's insane bro keep up the good work
Appreciate it
Great solution
Bhaiya can you please discuss the soln, for what happens if we can (sell and purchase) each transaction atmost k times and you must sell the stock before you buy the next stock
If the problem is extended to allow up to k transactions, the complexity increases, but it can still be solved using dynamic programming.
You'll need a two-dimensional array `profit[t][d]`, where `t` is the transaction index (from 0 to k) and `d` is the day index (from 0 to the number of days - 1). `profit[t][d]` represents the maximum profit we can get by making at most `t` transactions up to day `d`.
You can initialize `profit[t][0]` to 0 for all `t` (since you can't make a profit on the first day), and `profit[0][d]` to 0 for all `d` (since you can't make a profit with 0 transactions).
Then, you'll iterate over `t` and `d` to fill in the rest of the `profit` array. For each pair `(t, d)`, you have two options:
1. Don't make a transaction on day `d`. In this case, the profit is the same as it was on the previous day, i.e., `profit[t][d - 1]`.
2. Sell a stock on day `d`. In this case, you need to find the day to buy the stock that maximizes the profit. Let's call this day `d'`. You buy on day `d'` and sell on day `d`, and you also get the profit from making `t - 1` transactions up to day `d' - 1`. This gives you a profit of `prices[d] - prices[d'] + profit[t - 1][d' - 1]`. You'll take the maximum over all possible `d'` (from 0 to `d - 1`).
So, you'll fill in `profit[t][d]` as `max(profit[t][d - 1], prices[d] - prices[d'] + profit[t - 1][d' - 1] for all d' in [0, d - 1])`.
Finally, the maximum profit you can get is `profit[k][n - 1]`, where `n` is the number of days.
This solution has a time complexity of O(k*n^2) because for each pair `(t, d)`, it iterates over `[0, d - 1]` to find the best day `d'` to buy the stock.
The time complexity can be reduced to O(k*n) by keeping track of the maximum value of `prices[d'] - profit[t - 1][d' - 1]` for all `d'` in `[0, d - 1]`, and updating it for each `d`. This value represents the maximum profit you can get by ending your `t - 1`th transaction on or before day `d' - 1` and starting your `t`th transaction on day `d'`.
Here is the pseudo code for this:
```python
function maxProfit(prices, k):
n = len(prices)
if k > n / 2:
return quickSolve(prices) # quickSolve() is the function for unlimited transactions
profit = [[0]*n for _ in range(k+1)]
for t in range(1, k+1):
maxDiff = -prices[0]
for d in range(1, n):
profit[t][d] = max(profit[t][d - 1], prices[d] + maxDiff)
maxDiff = max(maxDiff, profit[t - 1][d - 1] - prices[d])
return profit[k][n - 1]
```
In this code, `maxDiff` is the maximum value of `profit[t - 1][d' - 1] - prices[d']` for all `d'` in `[0, d - 1]`. We update `maxDiff` for each `d` to ensure that it always represents the best day `d'` to buy the stock for the current transaction and day.
what if we are allowed to choose any number of time
but what if we want to get all the options to get max profit printed ?
To print all the transaction options for maximum profit, we need to slightly modify our approach. Along with tracking the maximum profit, we need to also track the decisions we made at each point.
After computing the maximum profit table, you can backtrack from `profit[k][n-1]` to find the transactions. If `profit[t][d]` is not equal to `profit[t][d - 1]`, it means we made a transaction on day `d`. We can then find the day `d'` we bought the stock by searching for `d'` such that `prices[d] - prices[d'] + profit[t - 1][d' - 1]` equals `profit[t][d]`. This is essentially the inverse of the computation we did to fill in the `profit` array.
This approach can be quite complex and time-consuming because for each transaction, you have to search for the day you bought the stock. An alternative approach is to store the decisions directly in another array during the dynamic programming step.
Here is a rough pseudo code for the entire approach:
```python
function maxProfit(prices, k):
n = len(prices)
if k > n / 2:
return quickSolve(prices) # quickSolve() is the function for unlimited transactions
profit = [[0]*n for _ in range(k+1)]
decision = [[0]*n for _ in range(k+1)] # new decision array
for t in range(1, k+1):
maxDiff = -prices[0]
for d in range(1, n):
if prices[d] + maxDiff > profit[t][d - 1]:
profit[t][d] = prices[d] + maxDiff
decision[t][d] = d # store the decision of making a transaction on day d
else:
profit[t][d] = profit[t][d - 1]
maxDiff = max(maxDiff, profit[t - 1][d - 1] - prices[d])
# backtracking to find the transactions
transactions = []
d = n - 1
for t in range(k, 0, -1):
if decision[t][d] != 0: # if we made a transaction on day d
buy_day = decision[t][d]
sell_day = d
transactions.append((buy_day, sell_day)) # add the transaction to the list
d = buy_day - 1 # move to the day before we bought the stock
return profit[k][n - 1], transactions[::-1] # reverse the transactions list to get them in chronological order
```
This code will return the maximum profit as well as the list of transactions. Each transaction is a pair `(buy_day, sell_day)` indicating the day you bought the stock and the day you sold it.
Please note that this pseudo code is simplified and assumes perfect inputs, so you should add your own error checking and edge case handling where necessary.
Answer is Seven
Thanks for the amazing explaination😊
Bhaiya thanks a lot for such a good content!
Bhaiya is question ke i think 6 variants hai kya please aap vo bhi discuss kr skte ho, thanks!!
this is pretty similar to kadanes algo
Understood
THANKS for everything ❤️❤️
Thank you for the wonderful series bro
If we give brute force first then optimal, won’t the interviewer say pata tha to pehle kyu nahi bataya (I’m genuinely asking, does this happen?)
Haha same question 😭😭😂
@@vagabondfoodie5788 no, by the time I realised, this is the correct process, first brute force then optimal
Understand
Nice explanation ❤
you are doing a good job man !
Man.. Thanks.. Subscribed
Superb Explanation!!
understood
thank you
how to initialize mini to some big integer in python ?
sys.maxsize
You are the best !!!
Thankyou for this explanation
Glad it was helpful!
Understood 💯
nicely explained sir
Understood bhaiya
Understood bro👍👍👍👍
Thanks bro
Helping a lot,
may all your dreams will happen
But one question, this is solved by u or some one ..., I ask one thing all the optimised solutions thought in your mind or took from some where,
Becoz I want to analyze my IQ, I didnt get any optimal solutions in my mind ,am I able to crack amazon
Sometimes it comes, sometime I understand!
@@takeUforward thanks bhai
Thank you Striver :)
U R BEST!
Great work, bro!
thank u striver
Awesome explanation bhaiya...Thanks a lot for providing great content and keep going and stay safe bhaiya.
Always welcome
loving your series :-) thanks a lot
No no someone else did :P
@@takeUforward next time se i will be first xD, without watching video becoz video to app acchi banaoge hi :)
Understood! Kudos for waiting me 🤣
Kadanes Algorithm !
understood bhaiya
Thank you! Cheers!
awesome explanation 😍
Thank you bro 💯💯
thank you so much bhaiya
you are a inspiration for me
It's my pleasure
bool understood = true ;p
hehe
Commenting for reach
thanku bhai u are great
US!!!
Understood
Thank you! Cheers!
Thanks bhai :)
Love u
Wishes
Thank you bhaiya
Nice
super 👌
Thanks for amazing video bhaiya
Video th dekh lo :P
is this a example of backtracking
cool