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
0
milindprajapatmst191 week ago
Total Time Taken: 0.03/1.17
Time Complexity: O(n*k)
Space Complexity: O(n*k) 
const int N = 500, K = 200, INF = 1e6;
int dp[N + 1][K + 1][2], f[] = {1, -1};
class Solution {
  public:
    int maxProfit(int k, int n, int arr[], int hold = 0) {
        if (k == 0 || n == 0)
            return hold ? -INF : 0;
        if (dp[n][k][hold] == -1)
            dp[n][k][hold] = max(maxProfit(k, n - 1, arr, hold), 
                                 maxProfit(k - hold, n - 1, arr, 1 - hold) + f[hold] * arr[n - 1]);
        return dp[n][k][hold];

    }
    Solution() {
        memset(dp, -1, sizeof(dp));
    }
};
0
sandeep55211 month ago
C++ Single 1-D array Space Optimized DP Solution(0.0 time taken)
int maxProfit(int k, int n, int p[]) {
       int c=k*2;
       vector<int> dp(c+1,0);
       for(int i=n-1;i>=0;i--){
           for(int j=c-1;j>=0;j--){
               if(j%2) dp[j]=max(p[i]+dp[j+1],dp[j]);
               else dp[j]=max(dp[j+1]-p[i],dp[j]);
           }
       }
       return dp[0];
   }
0
hamidnourashraf1 month ago
#O(N^2*K)
import math
class Solution:
    
    def maxProfit(self, K, N, A):
        dp = [[0] *(K+1) for j in range(N+1)]
        for k in range(1, K+1):
            for i in range(1, N+1):
                _max = -math.inf
                for j in range(1, i):
                    _max = max(_max, A[i-1] - A[j-1] + dp[j-1][k-1])
                dp[i][k] = max(_max, dp[i-1][k])
        return dp[N][K]
#O(N*K)
import math
class Solution:
    
    def maxProfit(self, K, N, A):
        dp = [[0] *(K+1) for j in range(N+1)]
        for k in range(1, K+1):
            pre_diff = -math.inf
            for i in range(1, N+1):
                pre_diff = max(pre_diff, -A[i-1] + dp[i-1][k-1])
                dp[i][k] = max(pre_diff + A[i-1], dp[i-1][k])
        return dp[N][K]
0
jaideepsinghsheoran1 month ago
int maxProfit(int k, int n, int p[]) {
        vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));
        for(int t = 1; t <= k; t++){
            int preComp = INT_MIN;
            for(int i = 1; i <= n; i++){
                preComp = max(preComp, dp[t-1][i-1] - p[i-1]);
                
                dp[t][i] = max(p[i-1] + preComp, dp[t][i-1]);
            }
        }
        return dp[k][n];
   }
0
jaideepsinghsheoran1 month ago
int maxProfit(int k, int n, int p[]) {
        vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));
        for(int t = 1; t <= k; t++){
            for(int i = 1; i <= n; i++){
                int maxProfitTill = INT_MIN;
                for(int j = 1; j < i; j++){
                    maxProfitTill = max(p[i-1] - p[j-1] + dp[t-1][j-1], maxProfitTill);
                }
                dp[t][i] = max(maxProfitTill, dp[t][i-1]);
            }
        }
        return dp[k][n];
   }
0
aditya048482 months ago
def maxProfit(self, k, n, prices):
        if n < 2:
            return 0
        dp = [[0 for j in range(k+1)] for i in range(n)]
        
        for j in range(1, k+1):
            maxDiff = -prices[0]
            for i in range(1, n):
                dp[i][j] = max(dp[i][j], dp[i-1][j], prices[i]+maxDiff)
                maxDiff = max(maxDiff, dp[i-1][j-1] - prices[i])
                
        return max(dp[n-1]) 
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(K*N) and space complexity as O(K*N) is as follows :-  
 
Execution Time :- 0.0 / 1.2 sec
 
int maxProfit(int K, int N, int A[]) {       vector<vector<int>> dp(K+1,vector<int>(N));       for(int i = 0; i <= K; i++){           for(int j = 0; j < N; j++){               if(i == 0 || j == 0)                   dp[i][j] = 0;           }       }              for(int i = 1; i <= K; i++){           int maxDiff = INT_MIN;           for(int j = 1; j < N; j++){               maxDiff = max(maxDiff,dp[i-1][j-1] - A[j-1]);               dp[i][j] = max(dp[i][j-1],maxDiff+A[j]);           }       }              return dp[K][N-1];   }
0
bhushan91682730332 months ago
C++ DP uncomment to see dp table:
int maxProfit(int K, int N, int A[]) {
	vector<vector<int>>dp(K + 1, vector<int>(N, 0));


	for (int i = 1; i <= K; i++)	{
		int maxDiff = INT_MIN;
		for (int j = 1; j < N; j++)	{
			maxDiff = max(maxDiff, (dp[i - 1][j - 1] - A[j - 1]));
			dp[i][j] = max(dp[i][j - 1], (A[j] + maxDiff));
		}
	}
	/*
	for (int i = 0; i <= K; i++)	{
		for (int j = 0; j < N; j++)	{
			cout << dp[i][j] << " ";
		}
		cout << endl;
	}*/

	return dp[K][N - 1];
}
0
sumitanand43993 months ago
BOTTOM-UP DP || 
 
class Solution { public:   int maxProfit(int k, int n, int prices[]) {       // code here              int dp[n+1][k+1][2];       memset(dp,0,sizeof(dp));       //vector<vector<vector<int>>> dp(n+1, vector<vector<int>> (k+1, vector<int>(2,0)));              for(int i=n-1; i>=0; i--)       {           for(int rem=1; rem<=k; rem++)           {               for(int hold=0; hold<2; hold++)               {                   int no= dp[i+1][rem][hold];                   int yes;                   if(hold==1) //selling stock                   {                       yes= prices[i] + dp[i+1][rem-1][0];                   }                   else //(hold==0) buying stock                   {                       yes= -prices[i] + dp[i+1][rem][1];                   }                   //recurrence relation                   dp[i][rem][hold]= max(no, yes);               }           }       }              return dp[0][k][0];   }};
 
 
0
safetymantu3 months ago
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.