Open In App

Minimum cost to build N blocks from one block

Given a number N, the task is to build N blocks from 1 block by performing following operation:

  1. Double the number of blocks present in the container and cost for this operation is X.
  2. Increase the number of blocks present in the container by one and cost for this operation is Y.
  3. Decrease the number of blocks present in the container by one and cost for this operation is Z.

Examples:



Input: N = 5, X = 2, Y = 1, Z = 3 
Output:
Explanation: 
In the first operation just increase the number of blocks by one, cost = 1 and block count = 2 
In the second operation double the blocks, cost = 3 and block count = 4 
In the third operation again increase the number_of_blocks by one, cost = 4 and block count = 5 
So minimum cost = 4 
Input: N = 7, X = 1, Y = 7, Z = 2 
Output: 5

Approach:



f(i) = min(f(i/2)+X, f(i-1)+Y, f(i+1)+Z)
f(i)=min(f(i/2)+X, f(i-1)+Y)
f(i)=min(f(i-1)+Y, f( (i+1)/2)+X+Z)

Below is the implementation of the above approach:




// C++ program to Minimum cost
// to build N blocks from one block
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate
// min cost to build N blocks
int minCost(int n, int x, int y, int z)
{
    int dp[n + 1] = { 0 };
 
    // Initialize base case
    dp[0] = dp[1] = 0;
 
    for (int i = 2; i <= n; i++) {
        // Recurrence when
        // i is odd
        if (i % 2 == 1) {
            dp[i] = min(
                dp[(i + 1) / 2] + x + z,
                dp[i - 1] + y);
        }
        // Recurrence when
        // i is even
        else {
            dp[i] = min(dp[i / 2] + x,
                        dp[i - 1] + y);
        }
    }
 
    return dp[n];
}
 
// Driver code
int main()
{
    int n = 5, x = 2, y = 1, z = 3;
    cout << minCost(n, x, y, z) << endl;
 
    return 0;
}




// Java program to Minimum cost
// to build N blocks from one block
class GFG
{
 
// Function to calculate
// min cost to build N blocks
static int minCost(int n, int x, int y, int z)
{
    int dp[] = new int[n + 1];
 
    // Initialize base case
    dp[0] = dp[1] = 0;
 
    for (int i = 2; i <= n; i++)
    {
        // Recurrence when
        // i is odd
        if (i % 2 == 1)
        {
            dp[i] = Math.min(
                dp[(i + 1) / 2] + x + z,
                dp[i - 1] + y);
        }
        // Recurrence when
        // i is even
        else
        {
            dp[i] = Math.min(dp[i / 2] + x,
                        dp[i - 1] + y);
        }
    }
 
    return dp[n];
}
 
// Driver code
public static void main(String[] args)
{
    int n = 5, x = 2, y = 1, z = 3;
    System.out.print(minCost(n, x, y, z) +"\n");
 
}
}
 
// This code is contributed by Rajput-Ji




# python3 program to Minimum cost
# to build N blocks from one block
 
# Function to calculate
# min cost to build N blocks
def minCost(n, x, y, z):
    dp = [0] * (n + 1)
 
    # Initialize base case
    dp[0] = dp[1] = 0
 
    for i in range(2, n + 1):
         
        # Recurrence when
        # i is odd
        if (i % 2 == 1):
            dp[i] = min(dp[(i + 1) // 2] + x + z, dp[i - 1] + y)
         
        # Recurrence when
        # i is even
        else:
            dp[i] = min(dp[i // 2] + x, dp[i - 1] + y)
 
    return dp[n]
 
# Driver code
n = 5
x = 2
y = 1
z = 3
print(minCost(n, x, y, z))
 
# This code is contributed by mohit kumar 29




// C# program to Minimum cost
// to build N blocks from one block
using System;
 
class GFG
{
 
// Function to calculate
// min cost to build N blocks
static int minCost(int n, int x, int y, int z)
{
    int []dp = new int[n + 1];
 
    // Initialize base case
    dp[0] = dp[1] = 0;
 
    for (int i = 2; i <= n; i++)
    {
        // Recurrence when
        // i is odd
        if (i % 2 == 1)
        {
            dp[i] = Math.Min(
                dp[(i + 1) / 2] + x + z,
                dp[i - 1] + y);
        }
         
        // Recurrence when
        // i is even
        else
        {
            dp[i] = Math.Min(dp[i / 2] + x,
                        dp[i - 1] + y);
        }
    }
    return dp[n];
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 5, x = 2, y = 1, z = 3;
    Console.Write(minCost(n, x, y, z) +"\n");
}
}
 
// This code is contributed by PrinciRaj1992




// JavaScript program to calculate the minimum cost
// to build N blocks from one block
 
function minCost(n, x, y, z) {
  let dp = new Array(n + 1).fill(0);
 
  // Initialize base case
  dp[0] = dp[1] = 0;
 
  for (let i = 2; i <= n; i++) {
    // Recurrence when i is odd
    if (i % 2 === 1) {
      dp[i] = Math.min(dp[(i + 1) / 2] + x + z, dp[i - 1] + y);
    }
    // Recurrence when i is even
    else {
      dp[i] = Math.min(dp[i / 2] + x, dp[i - 1] + y);
    }
  }
 
  return dp[n];
}
 
let n = 5, x = 2, y = 1, z = 3;
console.log(minCost(n, x, y, z));

Output

4

Time complexity :  O(N) 

Space complexity :  O(N) as a dp array of size N+1 is used.

Efficient approach : Space optimization

The previous implementation uses an array of size n+1 to store the minimum cost to build each number of blocks up to n. but we only need to keep track of the previous two minimum costs in order to compute the current minimum cost. Therefore, we can use just two variables to solve the problem.

Implementation steps:

Implementation:




#include <bits/stdc++.h>
using namespace std;
 
int minCost(int n, int x, int y, int z)
{   
      // Initialize base case
    int prev1 = 0, prev2 = 0;
     
      // iterate to get the computation of subproblmes
    for (int i = 2; i <= n; i++) {
          // to store current computation
        int cur;
        if (i % 2 == 1) {
            cur = min(prev1 + x + z, prev2 + y);
        }
        else {
            cur = min(prev1 + x, prev2 + y);
        }
       
          // assigning values to iterate further
        prev1 = prev2;
        prev2 = cur;
    }
     
      // return answer stored in prev2
    return prev2;
}
 
// Driver Code
int main()
{
    int n = 5, x = 2, y = 1, z = 3;
    cout << minCost(n, x, y, z) << endl;
 
    return 0;
}




import java.util.*;
 
public class MinCostCalculator {
 
    /**
     * Calculates the minimum cost to reach the nth step using given costs for different operations.
     *
     * @param n Number of steps
     * @param x Cost of operation 1
     * @param y Cost of operation 2
     * @param z Cost of operation 3
     * @return Minimum cost to reach the nth step
     */
    public static int minCost(int n, int x, int y, int z) {
        // Initialize base case
        int prev1 = 0, prev2 = 0;
 
        // Iterate to compute subproblems
        for (int i = 2; i <= n; i++) {
            // To store current computation
            int cur;
            if (i % 2 == 1) {
                // If the step is odd, consider the minimum cost of the three possible operations
                cur = Math.min(prev1 + x + z, prev2 + y);
            } else {
                // If the step is even, consider the minimum cost of two possible operations
                cur = Math.min(prev1 + x, prev2 + y);
            }
 
            // Assigning values to iterate further
            prev1 = prev2;
            prev2 = cur;
        }
 
        // Return the answer stored in prev2
        return prev2;
    }
 
    /**
     * Driver code to test the minCost function.
     */
    public static void main(String[] args) {
        // Test values
        int n = 5, x = 2, y = 1, z = 3;
 
        // Print the minimum cost for the given parameters
        System.out.println(minCost(n, x, y, z));
    }
}




def minCost(n: int, x: int, y: int, z: int) -> int:
    # Initialize base case
    prev1 = 0
    prev2 = 0
     
    # iterate to get the computation of subproblems
    for i in range(2, n + 1):
        # to store current computation
        if i % 2 == 1:
            cur = min(prev1 + x + z, prev2 + y)
        else:
            cur = min(prev1 + x, prev2 + y)
         
        # assigning values to iterate further
        prev1 = prev2
        prev2 = cur
     
    # return answer stored in prev2
    return prev2
 
# Driver Code
n = 5
x = 2
y = 1
z = 3
print(minCost(n, x, y, z))




using System;
 
class Program
{
    // Function to compute the minimum cost
    static int MinCost(int n, int x, int y, int z)
    {   
        // Initialize base cases
        int prev1 = 0, prev2 = 0;
         
        // Iterate to compute the values of subproblems
        for (int i = 2; i <= n; i++)
        {
            // Variable to store current computation
            int cur;
            if (i % 2 == 1)
            {
                cur = Math.Min(prev1 + x + z, prev2 + y);
            }
            else
            {
                cur = Math.Min(prev1 + x, prev2 + y);
            }
           
            // Assign values to iterate further
            prev1 = prev2;
            prev2 = cur;
        }
         
        // Return the answer stored in prev2
        return prev2;
    }
 
    // Main method
    static void Main(string[] args)
    {
        // Sample input values
        int n = 5, x = 2, y = 1, z = 3;
 
        // Compute and print the minimum cost
        Console.WriteLine(MinCost(n, x, y, z));
    }
}




function minCost(n, x, y, z) {
    // Initialize base case
    let prev1 = 0,
        prev2 = 0;
 
    // Iterate to get the computation of subproblems
    for (let i = 2; i <= n; i++) {
        // To store current computation
        let cur;
        if (i % 2 == 1) {
            cur = Math.min(prev1 + x + z, prev2 + y);
        } else {
            cur = Math.min(prev1 + x, prev2 + y);
        }
 
        // Assigning values to iterate further
        prev1 = prev2;
        prev2 = cur;
    }
 
    // Return answer stored in prev2
    return prev2;
}
 
let n = 5,
    x = 2,
    y = 1,
    z = 3;
console.log(minCost(n, x, y, z));

Output
4

Time complexity : O(N)

Auxiliary Space : O(1) 


Article Tags :