Open In App

Minimum cost to buy all items at least once

Last Updated : 28 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of length N. Consider that purchasing ith item will cost Ai and then next i number of item(s) will be free to collect. Then your task is to output the minimum cost to collect all items at least once.

Examples:

Input: A[] = {3 ,1, 2}

Output: 4

Explanation: Consider an imaginary array Collected[] to track collected items, collected items (free and purchased) and non-collected are denoted by 1 and 0 respectively. Thus, initially, Collected[] = {0, 0, 0}

  • Let us buy 1st item for cost A1 = 3. Then next 1 item (A2) will be available for free. Now, Collected[] updates to {1, 1, 0}.
  • Now, Buy 2nd item for cost A2 = 1. Then next 2 items will be available for free. As we can see that only one item A3 is left, therefore only one item can be considered as free. Formally, no A4 exists. Now, updated Collected[] becomes {1, 2, 1}. It must be noted that we can buy ith free item as well and then Collected[i] will also increment. It can be verified that all items are collected at least once and costs 3+1 = 4. Which is minimum possible.

Input: A[] = {1, 10, 1, 10, 10, 10}

Output: 2

Explanation:

  • Bought first item, it costs A1 = 1 and then A2 will be available for free. Cost till now = 1.
  • Buy 3rd item, it will cost A3 = 1 and next 3 items will be available for free, which are A4, A5, A6. All the items has collected at least once in total cost at 1+1 = 2. Which is minimum possible.

Approach: Implement the idea below to solve the problem

As we have choice to buy any element. Then, Dynamic Programming can be used to solve this problem. The main concept of DP in the problem will be:

  • DP[i] will store the minimum cost for buying first i number of item.
  • Transition: dp[i] = min(dp[i], dp[j – 1] + A[j])

Steps were taken to solve the problem:

  • Declaring DP[] array of length N.
  • Set base case as DP[0] = A[0]
  • Calculating answer for ith state by iterating from i = 1 to N – 1 and in each iteration follow below-mentioned steps:
    • Iterate from j = 1 to until i >= 2 * (j + 1) – 1 (iterate every element j from which ith index can be visited for free. if we visit j next 2 * (j + 1) – 1 elements can be visited for free)
      • In each iteration update DP[i] as min(DP[i], DP[j – 1] + A[i])
      • Make sure j -1 does not go out of bound add ternary case if j – 1 is out of bound then return 0 else return DP[j – 1].
  • Return DP[N – 1].

Code to implement the approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>;
using namespace std;
 
// Function to Minimum cost to buy all
// items at least once
int minimumCost(int A[], int N)
{
 
    // DP array initalized with infinity
    vector<int> dp(N + 1, 1e9);
 
    // Base case
    dp[0] = A[0];
 
    // Calculating answer for i'th item
    for (int i = 1; i < N; i++) {
 
        // Iterate if buying j'th item at cost
        // A[j] helps to buy i'th item for free
        for (int j = i; i <= (2 * (j + 1)) - 1; j--)
            dp[i] = min(dp[i], (j - 1 >= 0 ? dp[j - 1] : 0) + A[j]);
    }
 
    // Returing answer minimum cost
    // to buy all items at least once
    return dp[N - 1];
}
 
// Driver Code
int32_t main()
{
 
    // Input
    int N1 = 6;
    int A1[] = { 1, 10, 1, 10, 10, 10 };
 
    // Function Call
    cout << minimumCost(A1, N1) << endl;
 
    return 0;
}


Java




// Java code to implement the approach
class GFG {
    // Function to Minimum cost to buy all
    // items at least once
    static int minimumCost(int[] A, int N) {
 
        // DP array initialized with infinity
        int[] dp = new int[N + 1];
        for (int i = 0; i <= N; i++) {
            dp[i] = Integer.MAX_VALUE;
        }
 
        // Base case
        dp[0] = A[0];
 
        // Calculating answer for i'th item
        for (int i = 1; i < N; i++) {
 
            // Iterate if buying j'th item at cost
            // A[j] helps to buy i'th item for free
            for (int j = i; i <= (2 * (j + 1)) - 1; j--) {
                dp[i] = Math.min(
                        dp[i],
                        (j - 1 >= 0 ? dp[j - 1] : 0) + A[j]);
            }
        }
 
        // Returning answer minimum cost
        // to buy all items at least once
        return dp[N - 1];
    }
 
    // Driver Code
    public static void main(String[] args) {
 
        // Input
        int N1 = 6;
        int[] A1 = { 1, 10, 1, 10, 10, 10 };
 
        // Function Call
        System.out.println(minimumCost(A1, N1));
    }
}


Python3




def minimum_cost(A):
    N = len(A)
    # DP array initialized with infinity
    dp = [float('inf')] * N
 
    # Base case
    dp[0] = A[0]
 
    # Calculating answer for i'th item
    for i in range(1, N):
        # Iterate if buying j'th item at cost A[j] helps to buy i'th item for free
        for j in range(i, -1, -1):
            if i <= (2 * (j + 1)) - 1:
                dp[i] = min(dp[i], (dp[j - 1] if j - 1 >= 0 else 0) + A[j])
 
    # Returning answer minimum cost to buy all items at least once
    return dp[N - 1]
 
# Driver code
N1 = 6
A1 = [1, 10, 1, 10, 10, 10]
 
# Function call
print(minimum_cost(A1))


C#




using System;
 
class GFG {
    // Function to Minimum cost to buy all
    // items at least once
    static int MinimumCost(int[] A, int N)
    {
 
        // DP array initialized with infinity
        int[] dp = new int[N + 1];
        for (int i = 0; i <= N; i++) {
            dp[i] = int.MaxValue;
        }
 
        // Base case
        dp[0] = A[0];
 
        // Calculating answer for i'th item
        for (int i = 1; i < N; i++) {
 
            // Iterate if buying j'th item at cost
            // A[j] helps to buy i'th item for free
            for (int j = i; i <= (2 * (j + 1)) - 1; j--) {
                dp[i] = Math.Min(
                    dp[i],
                    (j - 1 >= 0 ? dp[j - 1] : 0) + A[j]);
            }
        }
 
        // Returning answer minimum cost
        // to buy all items at least once
        return dp[N - 1];
    }
 
    // Driver Code
    static void Main()
    {
 
        // Input
        int N1 = 6;
        int[] A1 = { 1, 10, 1, 10, 10, 10 };
 
        // Function Call
        Console.WriteLine(MinimumCost(A1, N1));
    }
}


Javascript




// Function to Minimum cost to buy all
// items at least once
function minimumCost(A, N) {
 
    // DP array initialized with infinity
    let dp = Array(N + 1).fill(Number.MAX_SAFE_INTEGER);
 
    // Base case
    dp[0] = A[0];
 
    // Calculating answer for i'th item
    for (let i = 1; i < N; i++) {
 
        // Iterate if buying j'th item at cost
        // A[j] helps to buy i'th item for free
        for (let j = i; i <= (2 * (j + 1)) - 1; j--) {
            dp[i] = Math.min(
                dp[i],
                (j - 1 >= 0 ? dp[j - 1] : 0) + A[j]
            );
        }
    }
 
    // Returning answer minimum cost
    // to buy all items at least once
    return dp[N - 1];
}
 
// Driver Code
let N1 = 6;
let A1 = [1, 10, 1, 10, 10, 10];
 
// Function Call
console.log(minimumCost(A1, N1));


Output

2










Time Complexity: O(N2)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads