Minimize cost of choosing and skipping array elements to reach end of the given array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int * cost , int n , int x ) { vector < int > dp ( n + 2 , 0 ) ; 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 ] + min ( dp [ i - 1 ] , x + dp [ i - 2 ] ) ; if ( i >= 3 ) dp [ i ] = cost [ i ] + min ( dp [ i - 1 ] , min ( x + dp [ i - 2 ] , 2 * x + dp [ i - 3 ] ) ) ; } cout << dp [ n - 1 ] ; } int main ( ) { int X = 4 ; int cost [ ] = { 6 , 3 , 9 , 2 , 1 , 3 } ; int N = sizeof ( cost ) / sizeof ( cost [ 0 ] ) ; minimumCost ( cost , N , X ) ; return 0 ; }