Open In App

Minimum cost to select K strictly increasing elements

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array and an integer K. Also given one more array which stores the cost of choosing elements from the first array. The task is to calculate the minimum cost of selecting K strictly increasing elements from the array.
Examples: 
 

Input: N = 4, K = 2
ele[] = {2, 6, 4, 8}
cost[] = {40, 20, 30, 10}
Output: 30
Explanation:
30 is the minimum cost by selecting elements
6 and 8 from the array with cost
10 + 20 respectively
Input: N = 11, K = 4
ele = {2, 6, 4, 8, 1, 3, 15, 9, 22, 16, 45}
cost = {40, 20, 30, 10, 50, 10, 20, 30, 40, 20, 10}
Output: 60
Explanation:
60 is the minimum cost by selecting elements
3, 15, 16, 45 from the array with cost
10 + 20 + 20 + 10 respectively

 

Approach: 
The given problem can be easily solved using a dynamic programming approach. As the problem asks for increasing elements and then minimum cost then it is clear that we have to move by either selecting ith or not selecting ith element one by one and calculate the minimum cost for each. 
Now, take a 3D DP array which stores our values of minimum cost, where cache[i][prev][cnt] stores the min-cost up to ith element, prev element and count of numbers considered till now.
There are 3 base conditions involved: 
 

  • If k elements are counted return 0.
  • If all elements of array has been traversed return MAX_VALUE.
  • Check if it’s already calculated in dp array.

Now comes the part of either selecting ith element or not selecting ith element: 
 

  • When ith elements is not considered ans = dp(i+1, prev, cnt, s, c)
  • When the ith element is greater than previous element, check if adding its cost makes total cost minimum ans = min(ans, c[i] + dp(i+1, i, cnt+1, s, c))

Below is the implementation of the above approach: 
 

CPP




// C++ program for
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
const int N = 1005;
const int K = 20;
int n, k;
int dp[N + 1][N + 1][K + 1];
 
// Function to calculate
// min cost to choose
// k increasing elements
int minCost(int i, int prev, int cnt,
                    int ele[], int cost[])
{
    // If k elements are
    // counted return 0
    if (cnt == k + 1) {
        return 0;
    }
 
    // If all elements
    // of array has been
    // traversed then
    // return MAX_VALUE
    if (i == n + 1) {
        return 1e5;
    }
 
    // To check if this is
    // already calculated
    int& ans = dp[i][prev][cnt];
    if (ans != -1) {
        return ans;
    }
 
    // When i'th elements
    // is not considered
    ans = minCost(i + 1, prev, cnt, ele, cost);
 
    // When the ith element
    // is greater than previous
    // element check if adding
    // its cost makes total cost minimum
    if (ele[i] > ele[prev]) {
        ans = min(ans, cost[i] + minCost(i + 1,
                           i, cnt + 1, ele, cost));
    }
    return ans;
}
 
// Driver code
int main()
{
 
    memset(dp, -1, sizeof(dp));
    n = 4;
    k = 2;
 
    int ele[n + 1] = { 0, 2, 6, 4, 8 };
 
    int cost[n + 1] = { 0, 40, 20, 30, 10 };
 
    int ans = minCost(1, 0, 1, ele, cost);
 
    if (ans == 1e5) {
        ans = -1;
    }
 
    cout << ans << endl;
 
    return 0;
}


Java




// C++ program for
// the above approach
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to calculate
    // min cost to choose
    // k increasing elements
    public static int minCost(int i, int prev, int cnt,
                              int ele[], int cost[], int n,
                              int k, int[][][] dp)
    {
        // If k elements are
        // counted return 0
        if (cnt == k + 1) {
            return 0;
        }
 
        // If all elements
        // of array has been
        // traversed then
        // return MAX_VALUE
        if (i == n + 1) {
            return 1000000;
        }
 
        // To check if this is
        // already calculated
        int ans = dp[i][prev][cnt];
        if (ans != -1) {
            return ans;
        }
 
        // When i'th elements
        // is not considered
        ans = minCost(i + 1, prev, cnt, ele, cost, n, k,
                      dp);
 
        // When the ith element
        // is greater than previous
        // element check if adding
        // its cost makes total cost minimum
        if (ele[i] > ele[prev]) {
            ans = Math.min(
                ans, (cost[i]
                      + minCost(i + 1, i, cnt + 1, ele,
                                cost, n, k, dp)));
        }
        return ans;
    }
    public static void main(String[] args)
    {
        int N = 1005;
        int K = 20;
        int n = 4, k = 2;
 
        int[][][] dp = new int[N + 1][N + 1][K + 1];
 
        // setting all values in dp = -1
        for (int[][] arr : dp)
            for (int[] row : arr)
                Arrays.fill(row, -1);
 
        int ele[] = { 0, 2, 6, 4, 8 };
 
        int cost[] = { 0, 40, 20, 30, 10 };
 
        int ans = minCost(1, 0, 1, ele, cost, n, k, dp);
 
        if (ans == 100000) {
            ans = -1;
        }
 
        System.out.println(ans);
        // This code is contributed by Aditya Sharma
    }
}


Python3




# Python3 program for
# the above approach
N = 1005;
K = 20;
 
n = 0
k = 0
 
dp = [[[-1 for k in range(K + 1)] for j in range(N + 1)] for i in range(N + 1)]
  
# Function to calculate
# min cost to choose
# k increasing elements
def minCost(i, prev, cnt, ele, cost):
 
    # If k elements are
    # counted return 0
    if (cnt == k + 1):
        return 0;
      
    # If all elements
    # of array has been
    # traversed then
    # return MAX_VALUE
    if (i == n + 1):
        return 100000;
     
    # To check if this is
    # already calculated
    ans = dp[i][prev][cnt];
     
    if (ans != -1):
        return ans;
     
    # When i'th elements
    # is not considered
    ans = minCost(i + 1, prev, cnt, ele, cost);
  
    # When the ith element
    # is greater than previous
    # element check if adding
    # its cost makes total cost minimum
    if (ele[i] > ele[prev]):
        ans = min(ans, cost[i] + minCost(i + 1, i, cnt + 1, ele, cost));
     
    return ans;
 
# Driver code
if __name__=='__main__':
  
    n = 4;
    k = 2;
  
    ele = [ 0, 2, 6, 4, 8 ]
  
    cost = [ 0, 40, 20, 30, 10 ]
  
    ans = minCost(1, 0, 1, ele, cost);
  
    if (ans == 100000):
        ans = -1;
     
    print(ans)
  
# This code is contributed by rutvik_56


C#




using System;
 
class GFG {
    // Function to calculate
    // min cost to choose
    // k increasing elements
    public static int minCost(int i, int prev, int cnt,
                              int[] ele, int[] cost, int n,
                              int k, int[, , ] dp)
    {
        // If k elements are
        // counted return 0
        if (cnt == k + 1) {
            return 0;
        }
        // If all elements
        // of array has been
        // traversed then
        // return MAX_VALUE
        if (i == n + 1) {
            return 1000000;
        }
 
        // To check if this is
        // already calculated
        int ans = dp[i, prev, cnt];
        if (ans != -1) {
            return ans;
        }
 
        // When i'th elements
        // is not considered
        ans = minCost(i + 1, prev, cnt, ele, cost, n, k,
                      dp);
 
        // When the ith element
        // is greater than previous
        // element check if adding
        // its cost makes total cost minimum
        if (ele[i] > ele[prev]) {
            ans = Math.Min(
                ans, (cost[i]
                      + minCost(i + 1, i, cnt + 1, ele,
                                cost, n, k, dp)));
        }
        return ans;
    }
    public static void Main(string[] args)
    {
        int N = 1005;
        int K = 20;
        int n = 4, k = 2;
 
        int[, , ] dp = new int[N + 1, N + 1, K + 1];
 
        // setting all values in dp = -1
        for (int i = 0; i <= N; i++)
            for (int j = 0; j <= N; j++)
                for (int l = 0; l <= K; l++)
                    dp[i, j, l] = -1;
 
        int[] ele = { 0, 2, 6, 4, 8 };
 
        int[] cost = { 0, 40, 20, 30, 10 };
 
        int ans = minCost(1, 0, 1, ele, cost, n, k, dp);
 
        if (ans == 1000000) {
            ans = -1;
        }
 
        Console.WriteLine(ans);
        // This code is contributed by Aditya Sharma
    }
}


Javascript




// JavaScript implementation of the above C++ code
 
// Function to calculate min cost to choose k increasing elements
function minCost(i, prev, cnt, ele, cost, n, k, dp) {
    // If k elements are counted, return 0
    if (cnt === k + 1) {
        return 0;
    }
 
    // If all elements of the array have been traversed, return MAX_VALUE
    if (i === n + 1) {
        return 1000000;
    }
 
    // To check if this is already calculated
    let ans = dp[i][prev][cnt];
    if (ans !== -1) {
        return ans;
    }
 
    // When the i'th element is not considered
    ans = minCost(i + 1, prev, cnt, ele, cost, n, k, dp);
 
    // When the i'th element is greater than the previous element,
    // check if adding its cost makes the total cost minimum
    if (ele[i] > ele[prev]) {
        ans = Math.min(ans, (cost[i] +
              minCost(i + 1, i, cnt + 1, ele, cost, n, k, dp)));
    }
    return ans;
}
 
const N = 1005;
const K = 20;
const n = 4, k = 2;
 
// Initialize a 3D array with all values set to -1
let dp = new Array(N + 1);
for (let i = 0; i <= N; i++) {
    dp[i] = new Array(N + 1);
    for (let j = 0; j <= N; j++) {
        dp[i][j] = new Array(K + 1).fill(-1);
    }
}
 
let ele = [0, 2, 6, 4, 8];
let cost = [0, 40, 20, 30, 10];
 
let ans = minCost(1, 0, 1, ele, cost, n, k, dp);
 
// If the answer is equal to MAX_VALUE, set it to -1
if (ans === 1000000) {
    ans = -1;
}
 
console.log(ans);


Output

30



Efficient approach : Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a DP to store the solution of the subproblems and initialize it with INT_MAX.
  • Initialize the DP with base cases
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP
  • Initialize a variable ans with INT_MAX to store the final answer and update it by iterating through the Dp.
  • At last return and print the final answer stored in ans .

Implementation :

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
const int N = 1005;
const int K = 20;
int n, k;
int dp[N + 1][K + 1];
 
// Function to calculate
// min cost to choose
// k increasing elements
int minCost(int ele[], int cost[])
{
    // Initializing dp table
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= k; j++) {
            dp[i][j] = INT_MAX;
        }
    }
    // Base case initialization
    for (int i = 1; i <= n; i++) {
        dp[i][1] = cost[i];
    }
 
    // DP tabulation
    for (int i = 2; i <= n; i++) {
        for (int j = 2; j <= k; j++) {
            for (int p = 1; p < i; p++) {
                if (ele[i] > ele[p]) {
                    // update DP
                    dp[i][j] = min(dp[i][j],
                                   cost[i] + dp[p][j - 1]);
                }
            }
        }
    }
 
    int ans = INT_MAX;
 
    // Finding the minimum cost
    for (int i = k; i <= n; i++) {
        ans = min(ans, dp[i][k]);
    }
 
    if (ans == INT_MAX) {
        ans = -1;
    }
 
    return ans;
}
 
// Driver code
int main()
{
    n = 4;
    k = 2;
    int ele[n + 1] = { 0, 2, 6, 4, 8 };
 
    int cost[n + 1] = { 0, 40, 20, 30, 10 };
 
    int ans = minCost(ele, cost);
 
    cout << ans << endl;
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
    static final int N = 1005;
    static final int K = 20;
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 4, k = 2;
        int[] ele = { 0, 2, 6, 4, 8 };
        int[] cost = { 0, 40, 20, 30, 10 };
 
        int ans = minCost(ele, cost, n, k);
 
        System.out.println(ans);
    }
 
    // Function to calculate
    // min cost to choose
    // k increasing elements
    public static int minCost(int[] ele, int[] cost, int n,
                              int k)
    {
 
        // Initializing dp table
        int[][] dp = new int[N + 1][K + 1];
 
        // Initializing dp table
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= k; j++) {
                dp[i][j] = Integer.MAX_VALUE;
            }
        }
 
        // Base case initialization
        for (int i = 1; i <= n; i++) {
            dp[i][1] = cost[i];
        }
 
        // DP tabulation
        for (int i = 2; i <= n; i++) {
            for (int j = 2; j <= k; j++) {
                for (int p = 1; p < i; p++) {
                    if (ele[i] > ele[p]) {
                        // update DP
                        dp[i][j] = Math.min(
                            dp[i][j],
                            cost[i] + dp[p][j - 1]);
                    }
                }
            }
        }
 
        int ans = Integer.MAX_VALUE;
 
        // Finding the minimum cost
        for (int i = k; i <= n; i++) {
            ans = Math.min(ans, dp[i][k]);
        }
 
        if (ans == Integer.MAX_VALUE) {
            ans = -1;
        }
 
        return ans;
    }
}


Python3




# Python program to calculate minimum cost to choose k increasing elements
 
# Function to calculate
# min cost to choose
# k increasing elements
def min_cost(ele, cost, n, k):
 
    # Initializing dp table
    dp = [[float('inf')] * (k + 1) for _ in range(n + 1)]
 
    # Base case initialization
    for i in range(1, n + 1):
        dp[i][1] = cost[i]
 
    # DP tabulation
    for i in range(2, n + 1):
        for j in range(2, k + 1):
            for p in range(1, i):
                if ele[i] > ele[p]:
                    # update DP
                    dp[i][j] = min(dp[i][j], cost[i] + dp[p][j - 1])
 
    ans = float('inf')
 
    # Finding the minimum cost
    for i in range(k, n + 1):
        ans = min(ans, dp[i][k])
 
    if ans == float('inf'):
        ans = -1
 
    return ans
 
 
# Driver Code
if __name__ == '__main__':
    n = 4
    k = 2
    ele = [0, 2, 6, 4, 8]
    cost = [0, 40, 20, 30, 10]
 
    ans = min_cost(ele, cost, n, k)
 
    print(ans)


C#




using System;
 
class GFG
{
    const int N = 1005;
    const int K = 20;
    static int n, k;
    static int[,] dp = new int[N + 1, K + 1];
 
    // Function to calculate
    // min cost to choose
    // k increasing elements
    static int minCost(int[] ele, int[] cost)
    {
        // Initializing dp table
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= k; j++)
            {
                dp[i, j] = int.MaxValue;
            }
        }
        // Base case initialization
        for (int i = 1; i <= n; i++)
        {
            dp[i, 1] = cost[i];
        }
 
        // DP tabulation
        for (int i = 2; i <= n; i++)
        {
            for (int j = 2; j <= k; j++)
            {
                for (int p = 1; p < i; p++)
                {
                    if (ele[i] > ele[p])
                    {
                        // update DP
                        dp[i, j] = Math.Min(dp[i, j], cost[i] + dp[p, j - 1]);
                    }
                }
            }
        }
 
        int ans = int.MaxValue;
 
        // Finding the minimum cost
        for (int i = k; i <= n; i++)
        {
            ans = Math.Min(ans, dp[i, k]);
        }
 
        if (ans == int.MaxValue)
        {
            ans = -1;
        }
 
        return ans;
    }
 
    // Driver code
    public static void Main()
    {
        n = 4;
        k = 2;
        int[] ele = { 0, 2, 6, 4, 8 };
 
        int[] cost = { 0, 40, 20, 30, 10 };
 
        int ans = minCost(ele, cost);
 
        Console.WriteLine(ans);
    }
}


Javascript




// JavaScript code for the above approach
 
function minCost(ele, cost, n, k) {
    const N = 1005;
    const K = 20;
 
    // Initializing the dp table
    const dp = new Array(N + 1).fill(null).map(() => new Array(K + 1).fill(0));
 
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= k; j++) {
            dp[i][j] = Number.MAX_SAFE_INTEGER;
        }
    }
 
    // Base case
    for (let i = 1; i <= n; i++) {
        dp[i][1] = cost[i];
    }
 
    // Tabulation
    for (let i = 2; i <= n; i++) {
        for (let j = 2; j <= k; j++) {
            for (let p = 1; p < i; p++) {
                if (ele[i] > ele[p]) {
                    // update DP
                    dp[i][j] = Math.min(
                        dp[i][j],
                        cost[i] + dp[p][j - 1]
                    );
                }
            }
        }
    }
 
    let ans = Number.MAX_SAFE_INTEGER;
 
    // Finding the minimum cost
    for (let i = k; i <= n; i++) {
        ans = Math.min(ans, dp[i][k]);
    }
 
    if (ans === Number.MAX_SAFE_INTEGER) {
        ans = -1;
    }
 
    return ans;
}
 
// Driver Code
const n = 4;
const k = 2;
const ele = [0, 2, 6, 4, 8];
const cost = [0, 40, 20, 30, 10];
 
const ans = minCost(ele, cost, n, k);
 
console.log(ans);
 
// This code is contributed by Abhinav Mahajan (abhinav_m22)


Output

30

Time complexity: O(N*K)

Auxiliary Space: O(N*K) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads