Stock Buy and Sell – At-most k Transactions Allowed
Last Updated :
18 Mar, 2025
In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions (a transaction is a combination of a buy and a sell), where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made.
Examples:
Input: prices = [10, 22, 5, 80], k = 2
Output: 87
Explanation: Buy on 1st day at 10 and sell on 2nd day at 22. Then, again buy on 3rd day at 5 and sell on 4th day at 80. Total profit = 12 + 75 = 87
Input: prices = [12, 14, 17, 10, 14, 13, 12, 15], k = 3
Output: 12
Explanation: Buy on 1st day and at 12 and sell on 3rd day at 17. Then, again buy on 4th day at 10 and sell on 5th day at 14. Lastly, buy on 7th day at 12 and sell on 8th day at 15. Total profit = 5 + 4 + 3 = 12
Input: prices = [100, 30, 15, 10, 8, 25, 80], k = 3
Output: 72
Explanation: Buy on 5th day at 8 and sell on 7th day at 80. Total profit = 72.
Input: prices = [90, 80, 70, 60, 50], k = 1
Output: 0
Explanation: Not possible to earn.
There are multiple variations of this problem. If only one buy and sell transaction is allowed, we can use the maximum difference between two elements approach. For at most two transactions, we can either follow the approach discussed here or use the given methods specifically for k=2. If unlimited transactions are permitted, we can adopt the strategy outlined here.
[Naive Approach] Using Recursion – O(2^n) time and O(n) space
To solve this problem, we need to analyze the possible decisions we can make on each day. Given a day i, we have three choices:
- Buy a stock (if we haven’t already bought one).
- Sell a stock (if we previously bought one).
- Do nothing and move to the next day without buying or selling.
The complexity of the problem arises because, for each day i, we must track both the number of remaining transactions and the state of our previous trade (whether we have bought or sold). To efficiently represent this, we define three states:
- i → The current day (index in the prices array).
- k → The number of transactions remaining.
- buy → A flag indicating whether we are in a buying state (1) or a selling state (0).
Recurrence Relation:
- If we can buy on day i: profit(i, k, 1) = profit(i + 1, k, 0) – prices[i]
- If we can sell on day i: profit(i, k, 0) = profit(i + 1, k – 1, 1) + prices[i]
- If we do nothing: profit(i, k, buy) = profit(i + 1, k, buy)
Return 0 if no transactions are left (k <= 0) or all days are processed (i >= n), otherwise return the maximum profit from the three cases.
C++
#include <bits/stdc++.h>
using namespace std;
// Utility function to calculate maximum profit
int maxProfitUtil(int i, int k, int buy,
vector<int> &prices){
// Base case: if no transactions left
// or end of price list is reached
if (k <= 0 || i >= prices.size())
return 0;
int result = 0, profit = 0;
// If we are in a 'buy' state
if (buy){
// Calculate profit by either buying
// at current price or skipping
profit = maxProfitUtil(i + 1, k, 0, prices)
- prices[i];
result = max(result, profit);
}
else{
// If in a 'sell' state, calculate profit
// by selling at current price
profit = prices[i] +
maxProfitUtil(i + 1, k - 1, 1, prices);
result = max(result, profit);
}
// Consider the option to skip the current
// price
profit = maxProfitUtil(i + 1, k, buy, prices);
return result = max(result, profit);
}
// Function to return max profit from k
// transation
int maxProfit(vector<int> &prices, int k){
// Start from first price, in 'buy' state
return maxProfitUtil(0, k, 1, prices);
}
int main(){
int k = 2;
vector<int> prices = {10, 22, 5, 80};
cout << maxProfit(prices, k) << endl;
return 0;
}
Java
import java.util.*;
class GfG {
// Utility function to calculate max profit
static int maxProfitUtil(int i, int k,
int buy,int[] prices){
// Base case: no transactions or end of list
if (k <= 0 || i >= prices.length)
return 0;
int result = 0, profit = 0;
// If we are in a 'buy' state
if (buy == 1){
// Buy at current price or skip
profit = maxProfitUtil(i + 1, k, 0,
prices) - prices[i];
result = Math.max(result, profit);
} else{
// Sell at current price or skip
profit = prices[i] +
maxProfitUtil(i + 1,k - 1,1,prices);
result = Math.max(result, profit);
}
// Skip current price
profit = maxProfitUtil(i + 1, k, buy,
prices);
return Math.max(result, profit);
}
// Function to return max profit with k
// transactions
static int maxProfit(int[] prices, int k){
// Start from first price in 'buy' state
return maxProfitUtil(0, k, 1, prices);
}
public static void main(String[] args){
int k = 2;
int[] prices = {10, 22, 5, 80};
System.out.println(maxProfit(prices, k));
}
}
Python
# Utility function to calculate max profit
def maxProfitUtil(i, k, buy, prices):
# Base case: no transactions or end of list
if k <= 0 or i >= len(prices):
return 0
result = 0
profit = 0
# If we are in a 'buy' state
if buy:
# Buy at current price or skip
profit = maxProfitUtil(i + 1, k, 0,
prices) - prices[i]
result = max(result, profit)
else:
# Sell at current price or skip
profit = prices[i] + maxProfitUtil(i + 1,
k - 1,1, prices)
result = max(result, profit)
# Skip current price
profit = maxProfitUtil(i + 1, k, buy, prices)
return max(result, profit)
# Function to return max profit with k transactions
def maxProfit(prices, k):
# Start from first price in 'buy' state
return maxProfitUtil(0, k, 1, prices)
if __name__ == "__main__":
k = 2
prices = [10, 22, 5, 80]
print(maxProfit(prices, k))
C#
using System;
class GfG {
// Utility function to calculate max profit
static int MaxProfitUtil(int i, int k, int buy,
int[] prices){
// Base case: no transactions or end of list
if (k <= 0 || i >= prices.Length)
return 0;
int result = 0, profit = 0;
// If we are in a 'buy' state
if (buy == 1) {
// Buy at current price or skip
profit = MaxProfitUtil(i + 1, k, 0, prices)
- prices[i];
result = Math.Max(result, profit);
}
else {
// Sell at current price or skip
profit = prices[i] + MaxProfitUtil(i + 1,
k - 1, 1, prices);
result = Math.Max(result, profit);
}
// Skip current price
profit = MaxProfitUtil(i + 1, k, buy, prices);
return Math.Max(result, profit);
}
// Function to return max profit with k
// transactions
static int maxProfit(int[] prices, int k){
return MaxProfitUtil(0, k, 1, prices);
}
static void Main(){
int k = 2;
int[] prices = { 10, 22, 5, 80 };
Console.WriteLine(maxProfit(prices, k));
}
}
JavaScript
// Utility function to calculate max profit
function maxProfitUtil(i, k, buy, prices){
// Base case: no transactions or end of list
if (k <= 0 || i >= prices.length)
return 0;
let result = 0, profit = 0;
// If we are in a 'buy' state
if (buy) {
// Buy at current price or skip
profit = maxProfitUtil(i + 1, k, 0, prices)
- prices[i];
result = Math.max(result, profit);
}
else {
// Sell at current price or skip
profit = prices[i]
+ maxProfitUtil(i + 1, k - 1, 1, prices);
result = Math.max(result, profit);
}
// Skip current price
profit = maxProfitUtil(i + 1, k, buy, prices);
return Math.max(result, profit);
}
// Function to return max profit with k transactions
function maxProfit(prices, k){
return maxProfitUtil(0, k, 1, prices);
}
const k = 2;
const prices = [ 10, 22, 5, 80 ];
console.log(maxProfit(prices, k));
Time Complexity: O(2n), exponential time
Auxiliary Space: O(n), due to recursion stack
[Better Approach-1] Using Memoization – O(n*k) time and O(n*k) space
The above approach involves multiple overlapping subproblems, leading to redundant computations. To optimize this, we can use memoization, which stores previously computed results and avoids recalculating them.
To achieve this, we maintain a 3D memoization array (memo) where:
memo[i][k][buy] stores the maximum profit achievable starting from day i, with k transactions remaining, and the current state (buy or sell).
By storing results for each unique combination of (i, k, buy), we ensure that once a state is computed, it doesn’t need to be recalculated, significantly improving efficiency.
C++
#include <bits/stdc++.h>
using namespace std;
// Utility function to calculate maximum profit
int maxProfitUtil(int i, int k, int buy, vector<vector<vector<int>>> &memo, vector<int> &prices)
{
// Base case: if no transactions left
// or end of price list is reached
if (k <= 0 || i >= prices.size())
return 0;
if (memo[i][k][buy] != -1)
return memo[i][k][buy];
int result = 0, profit = 0;
// If we are in a 'buy' state
if (buy)
{
// Calculate profit by either buying
// at current price or skipping
profit = maxProfitUtil(i + 1, k, 0, memo, prices) - prices[i];
result = max(result, profit);
}
else
{
// If in a 'sell' state, calculate profit
// by selling at current price
profit = prices[i] + maxProfitUtil(i + 1, k - 1, 1, memo, prices);
result = max(result, profit);
}
// Consider the option to skip the current
// price
profit = maxProfitUtil(i + 1, k, buy, memo, prices);
result = max(result, profit);
return memo[i][k][buy] = result;
}
// Function to return max profit from k
// transation
int maxProfit(vector<int> &prices, int k)
{
int n = prices.size();
// Initilize 3D vector for memoization
vector<vector<vector<int>>> memo(n + 1, vector<vector<int>>(k + 1, vector<int>(3, -1)));
// Start from first price, in 'buy' state
return maxProfitUtil(0, k, 1, memo, prices);
}
int main()
{
int k = 2;
vector<int> prices = {10, 22, 5, 80};
cout << maxProfit(prices, k) << endl;
return 0;
}
Java
import java.util.Arrays;
class GfG {
// Utility function to calculate max profit
static int maxProfitUtil(int i, int k, int buy,
int[][][] memo, int[] prices)
{
// Base case: no transactions or end of list
if (k <= 0 || i >= prices.length)
return 0;
if (memo[i][k][buy] != -1)
return memo[i][k][buy];
int result = 0, profit = 0;
// If we are in a 'buy' state
if (buy == 1) {
// Buy at current price or skip
profit
= maxProfitUtil(i + 1, k, 0, memo, prices)
- prices[i];
result = Math.max(result, profit);
}
else {
// Sell at current price
profit = prices[i]
+ maxProfitUtil(i + 1, k - 1, 1, memo,
prices);
result = Math.max(result, profit);
}
// Skip current price
profit = maxProfitUtil(i + 1, k, buy, memo, prices);
result = Math.max(result, profit);
memo[i][k][buy] = result;
return result;
}
// Function to return max profit with k transactions
static int maxProfit(int[] prices, int k)
{
int n = prices.length;
// Initialize memoization array
int[][][] memo = new int[n][k + 1][2];
for (int[][] arr2D : memo)
for (int[] arr1D : arr2D)
Arrays.fill(arr1D, -1);
// Start from first price in 'buy' state
return maxProfitUtil(0, k, 1, memo, prices);
}
public static void main(String[] args)
{
int k = 2;
int[] prices = { 10, 22, 5, 80 };
System.out.println(maxProfit(prices, k));
}
}
Python
# Utility function to calculate max profit
def maxProfitUtil(i, k, buy, memo, prices):
# Base case: no transactions or end of list
if k <= 0 or i >= len(prices):
return 0
if memo[i][k][buy] != -1:
return memo[i][k][buy]
result = 0
profit = 0
# If we are in a 'buy' state
if buy == 1:
# Buy at current price or skip
profit = maxProfitUtil(i + 1, k, 0, memo,
prices) - prices[i]
result = max(result, profit)
else:
# Sell at current price
profit = prices[i] + maxProfitUtil(i + 1,
k - 1, 1, memo, prices)
result = max(result, profit)
# Skip current price
profit = maxProfitUtil(i + 1, k, buy, memo,
prices)
result = max(result, profit)
memo[i][k][buy] = result
return result
# Function to return max profit with k transactions
def maxProfit(prices, k):
n = len(prices)
# Initialize memoization array
memo = [[[-1] * 2 for _ in range(k + 1)]
for _ in range(n)]
# Start from first price in 'buy' state
return maxProfitUtil(0, k, 1, memo, prices)
if __name__ == "__main__":
k = 2
prices = [10, 22, 5, 80]
print(maxProfit(prices, k))
C#
using System;
class GfG {
// Utility function to calculate max profit
static int MaxProfitUtil(int i, int k, int buy,
int[, , ] memo, int[] prices)
{
// Base case: no transactions or end of list
if (k <= 0 || i >= prices.Length)
return 0;
if (memo[i, k, buy] != -1)
return memo[i, k, buy];
int result = 0, profit = 0;
// If we are in a 'buy' state
if (buy == 1) {
// Buy at current price or skip
profit
= MaxProfitUtil(i + 1, k, 0, memo, prices)
- prices[i];
result = Math.Max(result, profit);
}
else {
// Sell at current price
profit = prices[i]
+ MaxProfitUtil(i + 1, k - 1, 1, memo,
prices);
result = Math.Max(result, profit);
}
// Skip current price
profit = MaxProfitUtil(i + 1, k, buy, memo, prices);
result = Math.Max(result, profit);
memo[i, k, buy] = result;
return result;
}
// Function to return max profit with k
// transactions
static int maxProfit(int[] prices, int k)
{
int n = prices.Length;
// Initialize memoization array
int[, , ] memo = new int[n, k + 1, 2];
for (int i = 0; i < n; i++)
for (int j = 0; j <= k; j++)
for (int b = 0; b < 2; b++)
memo[i, j, b] = -1;
// Start from first price in 'buy' state
return MaxProfitUtil(0, k, 1, memo, prices);
}
static void Main()
{
int k = 2;
int[] prices = { 10, 22, 5, 80 };
Console.WriteLine(maxProfit(prices, k));
}
}
JavaScript
function maxProfitUtil(i, k, buy, memo, prices)
{
// Base case: if no transactions left or
// end of price list is reached
if (k <= 0 || i >= prices.length)
return 0;
if (memo[i][k][buy] !== -1)
return memo[i][k][buy];
let result = 0, profit = 0;
// If we are in a 'buy' state
if (buy) {
// Calculate profit by either buying
// at current price or skipping
profit = maxProfitUtil(i + 1, k, 0, memo, prices)
- prices[i];
result = Math.max(result, profit);
}
else {
// If in a 'sell' state, calculate profit
// by selling at current price
profit = prices[i]
+ maxProfitUtil(i + 1, k - 1, 1, memo,
prices);
result = Math.max(result, profit);
}
// Consider the option to skip the current price
profit = maxProfitUtil(i + 1, k, buy, memo, prices);
result = Math.max(result, profit);
return memo[i][k][buy] = result;
}
// Function to return max profit from k transactions
function maxProfit(prices, k)
{
const n = prices.length;
// Initialize 3D array for memoization
const memo = Array.from(
{length : n + 1},
() => Array.from({length : k + 1},
() => Array(2).fill(-1)));
// Start from first price, in 'buy' state
return maxProfitUtil(0, k, 1, memo, prices);
}
const k = 2;
const prices = [ 10, 22, 5, 80 ];
console.log(maxProfit(prices, k));
Time Complexity: O(n*k)
Auxiliary Space: O(n*k)
[Better Approach-2] Using Bottom Up DP – O(n*k) time and O(n*k) space
The above solution can be further optimized using an iterative dynamic programming approach. Let dp[i][l][buy] represent the maximum profit achievable starting from day i, with l transactions remaining, and a state indicating whether we can buy or sell:
- buy = 1 → We are allowed to buy.
- buy = 0 → We are allowed to sell.
Recurrence Relation:
- Buy state (buy = 1): dp[i][l][1] = max(dp[i+1][l][0] – prices[i], dp[i+1][l][1])
- Sell state (buy = 0): dp[i][l][0] = max(prices[i] + dp[i+1][l-1][1], dp[i+1][l][0])
This iterative approach helps eliminate redundant recursive calls and improves efficiency.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to return max profit from k
// transactions
int maxProfit(vector<int> &prices, int k){
int n = prices.size();
if (n == 0 || k == 0)
return 0;
// DP table to store the maximum profit:
// dp[day][l][buy_or_sell]
vector<vector<vector<int>>> dp(n + 1,
vector<vector<int>>(k + 1,
vector<int>(2, 0)));
// Iterate from last day to the first (bottom-up)
for (int i = n - 1; i >= 0; i--){
for (int l = 1; l <= k; l++){
// Buy state
dp[i][l][1] = max(dp[i + 1][l][0]
- prices[i], dp[i + 1][l][1]);
// Sell state
dp[i][l][0] = max(prices[i]
+ dp[i + 1][l - 1][1], dp[i + 1][l][0]);
}
}
// Result is maximum profit starting from day 0,
// with k transactions, and in buy state
return dp[0][k][1];
}
int main(){
int k = 2;
vector<int> prices = {10, 22, 5, 80};
cout << maxProfit(prices, k) << endl;
return 0;
}
Java
class GfG {
// Function to return max profit from k
// transactions
static int maxProfit(int[] prices, int k){
int n = prices.length;
if (n == 0 || k == 0)
return 0;
// DP table
int[][][] dp = new int[n + 1][k + 1][2];
// Iterate from last day to first
for (int i = n - 1; i >= 0; i--) {
for (int l = 1; l <= k; l++) {
// Buy state
dp[i][l][1] = Math.max(dp[i + 1][l][0] - prices[i], dp[i + 1][l][1]);
// Sell state
dp[i][l][0] = Math.max(prices[i] + dp[i + 1][l - 1][1], dp[i + 1][l][0]);
}
}
return dp[0][k][1];
}
public static void main(String[] args){
int k = 2;
int[] prices = { 10, 22, 5, 80 };
System.out.println(maxProfit(prices, k));
}
}
Python
# Function to return max profit from k transactions
def maxProfit(prices, k):
n = len(prices)
if n == 0 or k == 0:
return 0
# DP table
dp = [[[0] * 2 for _ in range(k + 1)]
for _ in range(n + 1)]
# Iterate from last day to first
for i in range(n - 1, -1, -1):
for l in range(1, k + 1):
# Buy state
dp[i][l][1] = max(dp[i + 1][l][0] -
prices[i], dp[i + 1][l][1])
# Sell state
dp[i][l][0] = max(prices[i] +
dp[i + 1][l - 1][1], dp[i + 1][l][0])
return dp[0][k][1]
if __name__ == "__main__":
k = 2
prices = [10, 22, 5, 80]
print(maxProfit(prices, k))
C#
using System;
class GfG {
// Function to return max profit from k
// transactions
static int maxProfit(int[] prices, int k)
{
int n = prices.Length;
if (n == 0 || k == 0)
return 0;
// DP table
int[, , ] dp = new int[n + 1, k + 1, 2];
// Iterate from last day to first
for (int i = n - 1; i >= 0; i--) {
for (int l = 1; l <= k; l++) {
// Buy state
dp[i, l, 1]
= Math.Max(dp[i + 1, l, 0] -
prices[i], dp[i + 1, l, 1]);
// Sell state
dp[i, l, 0] = Math.Max(
prices[i] + dp[i + 1, l - 1, 1],
dp[i + 1, l, 0]);
}
}
return dp[0, k, 1];
}
static void Main(){
int k = 2;
int[] prices = { 10, 22, 5, 80 };
Console.WriteLine(maxProfit(prices, k));
}
}
JavaScript
// Function to return max profit from k
// transactions
function maxProfit(prices, k)
{
let n = prices.length;
if (n === 0 || k === 0)
return 0;
// DP table
let dp = Array.from({ length : n + 1},
() => Array.from({length : k + 1},
() => Array(2).fill(0)));
// Iterate from last day to first
for (let i = n - 1; i >= 0; i--) {
for (let l = 1; l <= k; l++) {
// Buy state
dp[i][l][1] = Math.max(dp[i + 1][l][0] -
prices[i], dp[i + 1][l][1]);
// Sell state
dp[i][l][0] = Math.max(prices[i] +
dp[i + 1][l - 1][1], dp[i + 1][l][0]);
}
}
return dp[0][k][1];
}
let k = 2;
let prices = [ 10, 22, 5, 80 ];
console.log(maxProfit(prices, k));
Time Complexity: O(n*k)
Auxiliary Space: O(n*k)
[Expected Approach] Space Optimized – O(n*k) time and O(k) space
Since for any day i, the calculations for dp[i][l][buy] only depend on dp[i+1][][] (the next day), we don’t need to store results for all previous days. Instead, we can reduce the DP table to just two 2D arrays:
- curr[l][buy] → Represents the profit on the current day for l transactions remaining and whether we are in a buy or sell state.
- next[l][buy] → Represents the profit for the next day.
This iterative approach optimizes space complexity, reducing it from O(k * n) to O(k) by only storing results for the current and next day instead of maintaining a full k × n DP table.
Optimized Recurrence Relation:
- Buy state: curr[l][1] = max(-prices[i] + next[l][0], next[l][1])
- Sell state: curr[l][0] = max(prices[i] + next[l-1][1], next[l][0])
C++
#include <bits/stdc++.h>
using namespace std;
// Function to return max profit from k transactions
int maxProfit(vector<int> &prices, int k){
int n = prices.size();
if (n == 0 || k == 0)
return 0;
vector<vector<int>> curr(k + 1, vector<int>(2, 0));
vector<vector<int>> next(k + 1, vector<int>(2, 0));
// Iterate from the last day to the first
for (int i = n - 1; i >= 0; i--){
for (int l = 1; l <= k; l++){
// Calculate for buy state
curr[l][1] = max(-prices[i] + next[l][0], next[l][1]);
// Calculate for sell state
curr[l][0] = max(prices[i] + next[l - 1][1], next[l][0]);
}
// Move current state to next, for the next iteration
next = curr;
}
return curr[k][1];
}
int main(){
int k = 2;
vector<int> prices = {10, 22, 5, 80};
cout << maxProfit(prices, k) << endl;
return 0;
}
Java
class GfG {
// Function to return max profit from k transactions
static int maxProfit(int[] prices, int k) {
int n = prices.length;
if (n == 0 || k == 0)
return 0;
int[][] curr = new int[k+1][2];
int[][] next = new int[k+1][2];
// Iterate from last day to first
for (int i = n - 1; i >= 0; i--) {
for (int l = 1; l <= k; l++) {
// Calculate for buy state
curr[l][1] = Math.max(-prices[i] + next[l][0], next[l][1]);
// Calculate for sell state
curr[l][0] = Math.max(prices[i] + next[l-1][1], next[l][0]);
}
// Move curr to next for next iteration
for (int l = 0; l <= k; l++) {
next[l][0] = curr[l][0];
next[l][1] = curr[l][1];
}
}
return curr[k][1];
}
public static void main(String[] args) {
int k = 2;
int[] prices = {10, 22, 5, 80};
System.out.println(maxProfit(prices, k));
}
}
Python
# Function to return max profit from k
# transactions
def maxProfit(prices, k):
n = len(prices)
if n == 0 or k == 0:
return 0
curr = [[0] * 2 for _ in range(k+1)]
next = [[0] * 2 for _ in range(k+1)]
# Iterate from last day to first
for i in range(n-1, -1, -1):
for l in range(1, k+1):
# Calculate for buy state
curr[l][1] = max(-prices[i] + next[l][0], next[l][1])
# Calculate for sell state
curr[l][0] = max(prices[i] + next[l-1][1], next[l][0])
# Move curr to next for next iteration
next = [row[:] for row in curr]
# The result is the maximum profit starting
# from day 0, with k transactions, and in
# buy state = 1 (this shows that transaction
# has been completed)
return curr[k][1]
if __name__ == "__main__":
k = 2
prices = [10, 22, 5, 80]
print(maxProfit(prices, k))
C#
using System;
class GfG {
// Function to return max profit from k
// transactions
static int maxProfit(int[] prices, int k) {
int n = prices.Length;
if (n == 0 || k == 0)
return 0;
int[,] curr = new int[k+1, 2];
int[,] next = new int[k+1, 2];
// Iterate from last day to first
for (int i = n - 1; i >= 0; i--) {
for (int l = 1; l <= k; l++) {
// Calculate for buy state
curr[l, 1] = Math.Max(next[l, 0] -
prices[i], next[l, 1]);
// Calculate for sell state
curr[l, 0] = Math.Max(prices[i] +
next[l - 1, 1], next[l, 0]);
}
// Move curr to next for next iteration
for (int l = 0; l <= k; l++) {
next[l, 0] = curr[l, 0];
next[l, 1] = curr[l, 1];
}
}
// The result is the maximum profit starting
// from day 0, with k transactions, and in
// buy state = 1 (this shows that transaction
// has been completed)
return curr[k, 1];
}
static void Main() {
int k = 2;
int[] prices = { 10, 22, 5, 80 };
Console.WriteLine(maxProfit(prices, k));
}
}
JavaScript
// Function to return max profit from k transactions
function maxProfit(prices, k) {
let n = prices.length;
if (n === 0 || k === 0) return 0;
let curr = Array.from({ length: k + 1 }, () =>
Array(2).fill(0));
let next = Array.from({ length: k + 1 }, () =>
Array(2).fill(0));
// Iterate from last day to first
for (let i = n - 1; i >= 0; i--) {
for (let l = 1; l <= k; l++) {
// Calculate for buy state
curr[l][1] = Math.max(-prices[i]
+ next[l][0], next[l][1]);
// Calculate for sell state
curr[l][0] = Math.max(prices[i] +
next[l - 1][1], next[l][0]);
}
// Move curr to next for next iteration
next = curr.map(row => row.slice());
}
return curr[k][1];
}
let k = 2;
let prices = [10, 22, 5, 80];
console.log(maxProfit(prices, k));
Time Complexity: O(n*k)
Auxiliary Space: O(k)
Similar Reads
Dynamic Programming or DP
Dynamic Programming is an algorithmic technique with the following properties. It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
What is Memoization? A Complete Tutorial
In this tutorial, we will dive into memoization, a powerful optimization technique that can drastically improve the performance of certain algorithms. Memoization helps by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant calcula
6 min read
Dynamic Programming (DP) Introduction
Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again. The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way
15+ min read
Tabulation vs Memoization
Tabulation and memoization are two techniques used to implement dynamic programming. Both techniques are used when there are overlapping subproblems (the same subproblem is executed multiple times). Below is an overview of two approaches. Memoization:Top-down approachStores the results of function c
9 min read
Optimal Substructure Property in Dynamic Programming | DP-2
The following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property. Let us discuss the Optimal Substructure property here.
4 min read
Overlapping Subproblems Property in Dynamic Programming | DP-1
Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem
10 min read
Steps to solve a Dynamic Programming Problem
Steps to solve a Dynamic programming problem:Identify if it is a Dynamic programming problem.Decide a state expression with the Least parameters.Formulate state and transition relationship.Apply tabulation or memorization.Step 1: How to classify a problem as a Dynamic Programming Problem? Typically,
14 min read
Advanced Topics
Count Ways To Assign Unique Cap To Every Person
Given n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps. Example: Input: caps = [[3, 4], [4, 5], [5]] Outpu
15+ min read
Digit DP | Introduction
Prerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers 'x' between two integers say 'a' and 'b' such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such intege
14 min read
Sum over Subsets | Dynamic Programming
Prerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
10 min read
Easy problems in Dynamic programming
Coin Change - Count Ways to Make Sum
Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
15+ min read
Subset Sum Problem
Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: arr[] = [3, 34,
15+ min read
Introduction and Dynamic Programming solution to compute nCr%p
Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is
15+ min read
Rod Cutting
Given a rod of length n inches and an array price[]. price[i] denotes the value of a piece of length i. The task is to determine the maximum value obtainable by cutting up the rod and selling the pieces. Note: price[] is 1-indexed array. Input: price[] = [1, 5, 8, 9, 10, 17, 17, 20]Output: 22Explana
15+ min read
Painting Fence Algorithm
Given a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color. Examples: Input: n = 2, k = 4Output: 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color: 4 Ways whe
15 min read
Longest Common Subsequence (LCS)
Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
15+ min read
Longest Increasing Subsequence (LIS)
Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest incre
14 min read
Longest subsequence such that difference between adjacents is one
Given an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1. Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], whe
15+ min read
Maximum size square sub-matrix with all 1s
Given a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s. Example: Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ] Output: 3Explanation: The maximum length of
15+ min read
Min Cost Path
You are given a 2D matrix cost[][] of dimensions m à n, where each cell represents the cost of traversing through that position. Your goal is to determine the minimum cost required to reach the bottom-right cell (m-1, n-1) starting from the top-left cell (0,0).The total cost of a path is the sum of
15+ min read
Longest Common Substring (Space optimized DP solution)
Given two strings âs1â and âs2â, find the length of the longest common substring. Example: Input: s1 = âGeeksforGeeksâ, s2 = âGeeksQuizâ Output : 5 Explanation:The longest common substring is âGeeksâ and is of length 5. Input: s1 = âabcdxyzâ, s2 = âxyzabcdâ Output : 4Explanation:The longest common s
7 min read
Count ways to reach the nth stair using step 1, 2 or 3
A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs. Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1}
15+ min read
Grid Unique Paths - Count Paths in matrix
Given an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down. Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
15+ min read
Unique paths in a Grid with Obstacles
Given a grid[][] of size m * n, let us assume we are starting at (1, 1) and our goal is to reach (m, n). At any instance, if we are on (x, y), we can either go to (x, y + 1) or (x + 1, y). The task is to find the number of unique paths if some obstacles are added to the grid.Note: An obstacle and sp
15+ min read
Medium problems on Dynamic programming
0/1 Knapsack Problem
Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Printing Items in 0/1 Knapsack
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
12 min read
Unbounded Knapsack (Repetition of items allowed)
Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
15+ min read
Egg Dropping Puzzle | DP-11
You are given n identical eggs and you have access to a k-floored building from 1 to k. There exists a floor f where 0 <= f <= k such that any egg dropped from a floor higher than f will break, and any egg dropped from or below floor f will not break. There are a few rules given below: An egg
15+ min read
Word Break
Given a string s and y a dictionary of n words dictionary, check if s can be segmented into a sequence of valid words from the dictionary, separated by spaces. Examples: Input: s = "ilike", dictionary[] = ["i", "like", "gfg"]Output: trueExplanation: The string can be segmented as "i like". Input: s
12 min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either âuâ or âvâ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complet
15+ min read
Tile Stacking Problem
Given integers n (the height of the tower), m (the maximum size of tiles available), and k (the maximum number of times each tile size can be used), the task is to calculate the number of distinct stable towers of height n that can be built. Note: A stable tower consists of exactly n tiles, each sta
15+ min read
Box Stacking Problem
Given three arrays height[], width[], and length[] of size n, where height[i], width[i], and length[i] represent the dimensions of a box. The task is to create a stack of boxes that is as tall as possible, but we can only stack a box on top of another box if the dimensions of the 2-D base of the low
15+ min read
Partition a Set into Two Subsets of Equal Sum
Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both. Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: T
15+ min read
Travelling Salesman Problem using Dynamic Programming
Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost. Note the differenc
15 min read
Longest Palindromic Subsequence (LPS)
Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Examples: Input: s = "bbabcbcab"Output: 7Explanation: Subsequence "babcbab" is the longest su
15+ min read
Longest Common Increasing Subsequence (LCS + LIS)
Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS. Examples: Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The lo
15+ min read
Find all distinct subset (or subsequence) sums of an array
Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small. Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
15+ min read
Weighted Job Scheduling
Given a 2D array jobs[][] of order n*3, where each element jobs[i] defines start time, end time, and the profit associated with the job. The task is to find the maximum profit you can take such that there are no two jobs with overlapping time ranges. Note: If the job ends at time X, it is allowed to
15+ min read
Count Derangements (Permutation such that no element appears in its original position)
A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of [0, 1, 2, 3] is [2, 3, 1, 0].Given a number n, find the total number of Derangements of a set of n elements. Examples : Input: n = 2Output: 1Explanation: For two balls [
12 min read
Minimum insertions to form a palindrome
Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Examples: Input: str = abcdOutput: 3Explanation: Here we can append 3 characters in the beginning, and the resultant string will be a palindrome ("dcbabcd"). Input: str = abaOutput: 0
15+ min read
Ways to arrange Balls such that adjacent balls are of different types
There are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of the same type are adjacent.Examples : Input: p = 1, q = 1, r = 0Output: 2Explanation: There are only two arrangements PQ and QP Input: p = 1, q = 1,
15+ min read