Stock Selling question

PLease give any hints .

@RAHUL hey,you can use dynamic programming here.Here is hint for recurrence relation:
Let profit[t][i] represent maximum profit using at most t transactions up to day i ,including day i. Then the recurrence relation is:
profit[t][i] = maximum(profit[t][i-1], max(price[i] – price[j] + profit[t-1][j]))
for all j in range [0, i-1]
profit[t][i] will be maximum of –
profit[t][i-1] which represents not doing any transaction on the ith day.
Maximum profit gained by selling on ith day. In order to sell shares on ith day, we need to purchase it on any one of [0, i – 1] days. If we buy shares on jth day and sell it on ith day, max profit will be price[i] – price[j] + profit[t-1][j] where j varies from 0 to i-1. Here profit[t-1][j] is best we could have done with one less transaction till jth day.
Hope you get it.Feel free to ask any doubt.Happy coding :slight_smile:

this is wrong , it should be like

profit[t][i] = maximum(profit[t][i-1], max(price[i] – price[j] + profit[t-1][j-1]))

it should be j-1 , because of non overlapping transactions

** if we are assuming that we bought at jth day, we should ensure that we were not selling at jth day **

please clarify this doubt

this is my code , watch at recursive calls

i have choose i+1, instead of i

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

@RAHUL why you have taken i+1 ,take i as index start from 0

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.