Minimum cost to buy N kilograms of sweet for M persons | Java program to minimum cost to buy N kilograms of sweet for M persons ; Function to find the minimum cost of sweets ; Defining the sweet array ; DP array to store the values ; Since index starts from 1 we reassign the array into sweet ; Assigning base cases for dp array ; At 0 it is free ; Package not available for desirable amount of sweets ; Buying the ' k ' kg package and assigning it to dp array ; If no solution , select from previous k - 1 packages ; If solution does not exist ; Print the solution ; Driver code ; Calling the desired function
public class GFG { static int find ( int m , int n , int adj [ ] ) { int sweet [ ] = new int [ n + 1 ] ; int dp [ ] [ ] [ ] = new int [ n + 1 ] [ n + 1 ] [ n + 1 ] ; sweet [ 0 ] = 0 ; for ( int i = 1 ; i <= m ; ++ i ) sweet [ i ] = adj [ i - 1 ] ; for ( int i = 0 ; i <= m ; ++ i ) { for ( int k = 0 ; k <= n ; ++ k ) dp [ i ] [ 0 ] [ k ] = 0 ; for ( int k = 1 ; k <= n ; ++ k ) dp [ i ] [ k ] [ 0 ] = - 1 ; } for ( int i = 0 ; i <= m ; ++ i ) { for ( int j = 1 ; j <= n ; ++ j ) { for ( int k = 1 ; k <= n ; ++ k ) { dp [ i ] [ j ] [ k ] = - 1 ; if ( i > 0 && j >= k && sweet [ k ] > 0 && dp [ i - 1 ] [ j - k ] [ k ] != - 1 ) dp [ i ] [ j ] [ k ] = dp [ i - 1 ] [ j - k ] [ k ] + sweet [ k ] ; if ( dp [ i ] [ j ] [ k ] == - 1 || ( dp [ i ] [ j ] [ k - 1 ] != - 1 && dp [ i ] [ j ] [ k ] > dp [ i ] [ j ] [ k - 1 ] ) ) dp [ i ] [ j ] [ k ] = dp [ i ] [ j ] [ k - 1 ] ; } } } if ( dp [ m ] [ n ] [ n ] == - 1 ) return 0 ; else return dp [ m ] [ n ] [ n ] ; } public static void main ( String args [ ] ) { int m = 3 ; int adj [ ] = { 2 , 1 , 3 , 0 , 4 , 10 } ; int n = adj . length ; System . out . println ( find ( m , n , adj ) ) ; } }