Minimize cost of choosing and skipping array elements to reach end of the given array | Java program for the above approach ; Function to find the minimum cost to reach the end of the array from the first element ; Store the results ; Consider first index cost ; Find answer for each position i ; First Element ; Second Element ; For remaining element ; Consider min cost for skipping ; Last index represents the minimum total cost ; Driver Code ; Given X ; Given array cost [ ] ; Function Call
import java . io . * ; import java . util . * ; class GFG { static void minimumCost ( int [ ] cost , int n , int x ) { int [ ] dp = new int [ n + 2 ] ; dp [ 0 ] = cost [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( i == 1 ) dp [ i ] = cost [ i ] + dp [ i - 1 ] ; if ( i == 2 ) dp [ i ] = cost [ i ] + Math . min ( dp [ i - 1 ] , x + dp [ i - 2 ] ) ; if ( i >= 3 ) dp [ i ] = cost [ i ] + Math . min ( dp [ i - 1 ] , Math . min ( x + dp [ i - 2 ] , 2 * x + dp [ i - 3 ] ) ) ; } System . out . println ( dp [ n - 1 ] ) ; } public static void main ( String [ ] args ) { int X = 4 ; int [ ] cost = { 6 , 3 , 9 , 2 , 1 , 3 } ; int N = cost . length ; minimumCost ( cost , N , X ) ; } }