Maximum Profit | Practice | GeeksforGeeks

In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of N days in an array A[ ] and a positive integer K, find out the maximum profit a person can make in at-most K transactions. A transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous transaction has been completed.

Example 1:
Input: K = 2, N = 6
A = {10, 22, 5, 75, 65, 80}
Output: 87
Explaination: 
1st transaction: buy at 10 and sell at 22. 
2nd transaction : buy at 5 and sell at 80.

Example 2:
Input: K = 3, N = 4
A = {20, 580, 420, 900}
Output: 1040
Explaination: The trader can make at most 2 
transactions and giving him a profit of 1040.

Example 3:
Input: K = 1, N = 5
A = {100, 90, 80, 50, 25}
Output: 0
Explaination: Selling price is decreasing 
daily. So seller cannot have profit.

Your Task:
You do not need to read input or print anything. Your task is to complete the function maxProfit() which takes the values K, N and the array A[] as input parameters and returns the maximum profit.

Expected Time Complexity: O(N*K)
Expected Auxiliary Space: O(N*K)

Constraints:
1 ≤ N ≤ 500
1 ≤ K ≤ 200
1 ≤ A[ i ] ≤ 1000
+1
goyalshivank7902 days ago
// easy c++ solution
 
int maxProfit(int K, int N, int A[]) {       int dp[K+1][N];       memset(dp,0,sizeof(dp));       for(int i=1;i<=K;i++){           int maxm = INT_MIN;           for(int j=1;j<N;j++){               maxm = max(dp[i-1][j-1]-A[j-1],maxm);               dp[i][j] = max(dp[i][j-1],maxm + A[j]);           }       }       return dp[K][N-1];   }
0
akkeshri140420014 days ago
int maxProfit(int K, int N, int A[]) {
       // code here
       vector<vector<int>>dp(K+1,vector<int>(N));
       for(int i=0;i<K+1;i++){
           for(int j=0;j<N;j++){
               if(i==0 or j==0){
                   dp[i][j]=0;
               }
           }
       }
       for(int i=1;i<K+1;i++){
           int maxi=INT_MIN;
           for(int j=1;j<N;j++){
            maxi=max(maxi,dp[i-1][j-1]-A[j-1]);
            dp[i][j]=max(maxi+A[j],dp[i][j-1]);
           }
       }
       return dp[K][N-1];
   }
0
onlybkm20021 week ago
int f(int index, int buy ,int n, int cap, int arr[], vector<vector<vector<int>>> &dp)
    {
        if(index == n || cap == 0)
        {
            return 0;
        }
        if(dp[index][buy][cap] != -1)
        {
            return dp[index][buy][cap];
        }
        int profit;
        if(buy == 1)
        {
            profit = max(f(index+1,0,n,cap,arr,dp)-arr[index],f(index+1,1,n,cap,arr,dp));
        }
        else{
            profit = max(f(index+1,1,n,cap-1,arr,dp)+arr[index],f(index+1,0,n,cap,arr,dp));
        }
        return  dp[index][buy][cap] = profit;    
        
    }

    int maxProfit(int K, int N, int A[]) {
        // code here
         vector<vector<vector<int>>> dp(N,
                                    vector<vector<int>> 
                                            (2,vector<int>(K+1,-1)));
        return f(0,1,N,K,A,dp);
    }
+1
kelvin_01791 week ago
Remember that you have a choice at every point so don't always buy the first stock , cost me 1 WA
 
  class Solution {
  public:
    int n,k;
    vector<vector<int>> dp;
    int dynamic(int indx,int lft,int c[]){
        if(lft==0 or indx==n){
            return 0;
        }
        if(dp[indx][lft]!=-1){
            return dp[indx][lft];
        }
        int ans=dynamic(indx+1,lft,c);
        for(int i=indx+1;i<n;i++){
            ans=max(ans,max(0,c[i]-c[indx]+dynamic(i+1,lft-1,c)));
        }
        return dp[indx][lft]=ans;
    }
    int maxProfit(int k, int n, int c[]) {
        // code here
        this->n=n;
        this->k=k;
        dp=vector<vector<int>>(n,vector<int>(k+1,-1));
        return dynamic(0,k,c);
    }
};
0
ankukumar74241 week ago
Easy dp solution*****
class Solution { public: int solve(int ind,int buy,int K,int N,int A[],vector<vector<vector<int>>>& dp){     if(ind==N ||  K==0)return 0;     if(dp[ind][buy][K]!=-1)return dp[ind][buy][K];     if(buy){         dp[ind][buy][K]=max(-A[ind]+solve(ind+1,0,K,N,A,dp),solve(ind+1,1,K,N,A,dp));     }     else{         dp[ind][buy][K]=max(A[ind]+solve(ind+1,1,K-1,N,A,dp),solve(ind+1,0,K,N,A,dp));     }     return dp[ind][buy][K]; }   int maxProfit(int K, int N, int A[]) {       // code here       vector<vector<vector<int>>> dp(N,vector<vector<int>>(2,vector<int>(K+1,-1)));       return solve(0,1,K,N,A,dp);   }}; 
0
ritikk51882 weeks ago
 int solve(int i,int j ,int k,int arr[],int n,vector<vector<vector<int>>> &dp){     if(dp[i][j][k]!=-1)        return dp[i][j][k];     if(k==0)       return(0);     if(i==n)        return 0;      if(j==1)          return dp[i][j][k]=max(-arr[i]+solve(i+1,0,k,arr,n,dp),solve(i+1,1,k,arr,n,dp));       else           return  dp[i][j][k]= max(arr[i]+solve(i+1,1,k-1,arr,n,dp),solve(i+1,0,k,arr,n,dp)); }   int maxProfit(int K, int N, int A[]) {       vector<vector<vector<int>>> dp(N+1,vector<vector<int>>(2,vector<int>(K+1,-1)));       vector<vector<int>> next(2,vector<int>(K+1,0));       for(int i=N;i>=0;i--){           vector<vector<int>> curr(2,vector<int>(K+1,0));           for(int j=0;j<=1;j++){               for(int p=0;p<=K;p++){                   if(i==N)                     curr[j][p]=0;                   else if(p==0)                      curr[j][p]=0;                   else{                        if(j==1)                            curr[j][p]=max(-A[i]+next[0][p],next[1][p]);                        else                            curr[j][p]=max(A[i]+next[1][p-1],next[0][p]);                   }                  }           }           next=curr;       }          return(next[1][K]);       //return solve(0,1,K,A,N,dp);
0
nilkantr1232 weeks ago
simple memoization
int dp[501][201];
  int solve(int arr[], int n, int k, int buy, int index, int prev){
      if(k == 0) return 0;
      
      if(dp[index][k] != -1)
      return dp[index][k];
      
      int res = 0;
      if(buy == 1){
          for(int i=index; i<n; i++){
              int profit = solve(arr, n, k-1, 0, i+1, arr[i]);
              res = max(profit, res);
          }
      }
      else{
          for(int i=index; i<n; i++){
              if(arr[i] > prev){
                  int profit2 = arr[i] - prev + solve(arr, n, k-1, 1, i+1, -1);
                  res = max(res, profit2);
              }
          }
      }
      return dp[index][k] =  res;
  }
  
    int maxProfit(int K, int N, int A[]) {
        // code here
        memset(dp, -1, sizeof(dp));
        return solve(A, N, 2*K, 1, 0, -1);
    }
0
dassourabh143 weeks ago
Easy C++ || DP
int maxProfit(int k, int n, int A[]) {
        int dp[k+1][n];
        for(int i=0;i<=k;i++) dp[i][0]=0;
        for(int j=0;j<n;j++) dp[0][j]=0;
        
        for(int i=1;i<=k;i++){
            int pmax=INT_MIN;
            for(int j=1;j<n;j++){
                pmax=max(pmax, dp[i-1][j-1]-A[j-1]);
                dp[i][j]=max(pmax+A[j], dp[i][j-1]);
            }
        }
        return dp[k][n-1];
    }
0
shubham4093 weeks ago
Solution in Java :- 
Using Memoization and 2D array.
 
class Solution {
    private static int[] price;
    static int length ;
    static int [][] dp;
    static int maxProfit(int K, int N, int[] A) {
        price = A;
        K = 2*K;
        length = N;
        dp = new int[N+1][K+1];
        for (int i = 0; i < N+1; i++) {
            for (int j = 0; j < K+1; j++) {
                dp[i][j] = Integer.MIN_VALUE;
            }
        }
        return recurstion(0,K);
    }
    public static int recurstion(int i , int remiaining_purchases){
        if (remiaining_purchases == 0 || i==length ){
            return 0;
        }

        else if (remiaining_purchases%2==0){
//            buy or ignore
            if (dp[i][remiaining_purchases] != Integer.MIN_VALUE)
                return dp[i][remiaining_purchases];
            dp[i][remiaining_purchases] = Math.max(-price[i]+recurstion(i+1,remiaining_purchases-1),recurstion(i+1,remiaining_purchases));
            return dp[i][remiaining_purchases];
        }
        else{
//          sell or ignor
            if (dp[i][remiaining_purchases] != Integer.MIN_VALUE)
                return dp[i][remiaining_purchases];
            dp[i][remiaining_purchases] = Math.max(price[i]+recurstion(i+1,remiaining_purchases-1),recurstion(i+1,remiaining_purchases));
            return dp[i][remiaining_purchases];

        }
    }
}
Simple solution in java using 2d array.
Use -ive price when buy and +ive when to sellUse even-odd concept to track whether previously it was bought or sold.              For this double transactions first.Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even.
Use -ive price when buy and +ive when to sell
Use even-odd concept to track whether previously it was bought or sold.              For this double transactions first.Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even.
Always sell or ignore when current transaction is odd.Always buy or ignore when current transaction is even.
Always sell or ignore when current transaction is odd.
Always buy or ignore when current transaction is even.
0
simhachalammadireddi3 weeks ago
 int maxProfit(int K, int N, int A[]) {       vector<vector<int>>dp(N+1,vector<int>(2*K+1,0));       for(int ind=N-1;ind>=0;ind--)       {                    for(int k=2*K-1;k>=0;k--)           {                 if(k%2==0)                   dp[ind][k]=max(-A[ind]+dp[ind+1][k+1],dp[ind+1][k]);                 else                    dp[ind][k]=max(A[ind]+dp[ind+1][k+1],dp[ind+1][k]);           }                }       return dp[0][0];   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.