Advertisement
imashutosh51

Maximum profits in stock

Jul 31st, 2022
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. /*
  2.  Logic: we used a dp table whose row denotes the number of transactions and column denotes the stocks prices daywise.
  3.  so dp[i][j] is equal to maximum profit acheived till jth day after i transactions.
  4.  
  5.  using 0 transactions,no profit can be earned so 0th row will be filed with 0.
  6.  using any number of transaction in one day only,no profit can be earned because stock
  7.  price doesn't changing same day.
  8.  
  9.  for eg i=2 and j=5
  10.  now,using i transactions,and at jth day,maxium profit will be:
  11.  either do i transaaction till j-1th day ie. dp[i][j-1]  
  12.  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]
  13.  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]
  14.  .                                                                                                  ie. dp[1][2]+arr[5]-arr[2]
  15.  .
  16.  .
  17.  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]
  18.  so,arr[5] is common in above example ie. stock price of current day
  19.  so max_val will store the value of maximum profit of i-1th transaction - stock price at that day so if we will add
  20.  the stock price of jth day then we will have maximum of last transaction completed on jth day.
  21.  
  22. */
  23. class Solution {
  24.   public:
  25.     int maxProfit(int k, int n, int arr[]) {
  26.         int dp[201][501];
  27.         memset(dp,0,sizeof(dp));
  28.         for(int i=1;i<=k;i++){
  29.             int max_val=INT_MIN;
  30.             for(int j=1;j<n;j++){
  31.                  max_val=max(max_val,dp[i-1][j-1]-arr[j-1]);  // update max_val if profit till last transaction-last day price
  32.                  dp[i][j]=max(max_val+arr[j],dp[i][j-1]);     //is greater than max_val
  33.             }
  34.         }
  35.         return dp[k][n-1];
  36.     }
  37. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement