Minimum total sum from the given two arrays | C ++ program for the above approach ; Function that prints minimum sum after selecting N elements ; Initialise the dp array ; Base Case ; Adding the element of array a if previous element is also from array a ; Adding the element of array a if previous element is from array b ; Adding the element of array b if previous element is from array a with an extra penalty of integer C ; Adding the element of array b if previous element is also from array b ; Print the minimum sum ; Driver Code ; Given array arr1 [ ] and arr2 [ ] ; Given cost ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSum ( int a [ ] , int b [ ] , int c , int n ) { vector < vector < int > > dp ( n , vector < int > ( 2 , 1e6 ) ) ; dp [ 0 ] [ 0 ] = a [ 0 ] ; dp [ 0 ] [ 1 ] = b [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) ; dp [ i ] [ 0 ] = min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 1 ] + a [ i ] + c ) ; dp [ i ] [ 1 ] = min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + b [ i ] + c ) ; dp [ i ] [ 1 ] = min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 1 ] + b [ i ] ) ; } cout << min ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) << " STRNEWLINE " ; } int main ( ) { int arr1 [ ] = { 7 , 6 , 18 , 6 , 16 , 18 , 1 , 17 , 17 } ; int arr2 [ ] = { 6 , 9 , 3 , 10 , 9 , 1 , 10 , 1 , 5 } ; int C = 2 ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; minimumSum ( arr1 , arr2 , C , N ) ; return 0 ; }