Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic: we used a dp table whose row denotes the number of transactions and column denotes the stocks prices daywise.
- so dp[i][j] is equal to maximum profit acheived till jth day after i transactions.
- using 0 transactions,no profit can be earned so 0th row will be filed with 0.
- using any number of transaction in one day only,no profit can be earned because stock
- price doesn't changing same day.
- for eg i=2 and j=5
- now,using i transactions,and at jth day,maxium profit will be:
- either do i transaaction till j-1th day ie. dp[i][j-1]
- or do i-1 transaction till day 0 and last transaction or ith transaction between day 0 to jth day ie. dp[1][0]+arr[5]-arr[0]
- or do i-1 transaction till day 1 and last transaction or ith transaction between day 1 to jth day ie. dp[1][1]+arr[5]-arr[1]
- . ie. dp[1][2]+arr[5]-arr[2]
- .
- .
- or do i-1th transaction till j-1 day and last transaction or ith transaction between day j-1 to jth day ie. dp[1][4]+arr[5]-arr[4]
- so,arr[5] is common in above example ie. stock price of current day
- so max_val will store the value of maximum profit of i-1th transaction - stock price at that day so if we will add
- the stock price of jth day then we will have maximum of last transaction completed on jth day.
- */
- class Solution {
- public:
- int maxProfit(int k, int n, int arr[]) {
- int dp[201][501];
- memset(dp,0,sizeof(dp));
- for(int i=1;i<=k;i++){
- int max_val=INT_MIN;
- for(int j=1;j<n;j++){
- max_val=max(max_val,dp[i-1][j-1]-arr[j-1]); // update max_val if profit till last transaction-last day price
- dp[i][j]=max(max_val+arr[j],dp[i][j-1]); //is greater than max_val
- }
- }
- return dp[k][n-1];
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement