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