Minimum total sum from the given two arrays | 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 ; Given array arr1 [ ] and arr2 [ ] ; Given cost ; Function call
function minimumSum ( a , b , c , n ) { let dp = new Array ( n ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < 2 ; j ++ ) { dp [ i ] [ j ] = 1e6 ; } } dp [ 0 ] [ 0 ] = a [ 0 ] ; dp [ 0 ] [ 1 ] = b [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = Math . min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) ; dp [ i ] [ 0 ] = Math . min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 1 ] + a [ i ] + c ) ; dp [ i ] [ 1 ] = Math . min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + b [ i ] + c ) ; dp [ i ] [ 1 ] = Math . min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 1 ] + b [ i ] ) ; } document . write ( Math . min ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) + " " ) ; } let arr1 = [ 7 , 6 , 18 , 6 , 16 , 18 , 1 , 17 , 17 ] ; let arr2 = [ 6 , 9 , 3 , 10 , 9 , 1 , 10 , 1 , 5 ] ; let C = 2 ; let N = arr1 . length ; minimumSum ( arr1 , arr2 , C , N ) ;