Minimize the sum after choosing elements from the given three arrays | Javascript implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen previously then only B [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If B [ i - 1 ] was chosen previously then only A [ i ] or C [ i ] can chosen now choose the one which leads to the minimum sum ; If C [ i - 1 ] was chosen previously then only A [ i ] or B [ i ] can chosen now choose the one which leads to the minimum sum ; Driver code ; Initialize the dp [ ] [ ] array ; min ( start with A [ 0 ] , start with B [ 0 ] , start with C [ 0 ] )
let SIZE = 3 ; let N = 3 ; function minSum ( A , B , C , i , n , curr , dp ) { if ( n <= 0 ) return 0 ; if ( dp [ n ] [ curr ] != - 1 ) return dp [ n ] [ curr ] ; if ( curr == 0 ) { return dp [ n ] [ curr ] = Math . min ( B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; } if ( curr == 1 ) return dp [ n ] [ curr ] = Math . min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , C [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 2 , dp ) ) ; return dp [ n ] [ curr ] = Math . min ( A [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 0 , dp ) , B [ i ] + minSum ( A , B , C , i + 1 , n - 1 , 1 , dp ) ) ; } let A = [ 1 , 50 , 1 ] ; let B = [ 50 , 50 , 50 ] ; let C = [ 50 , 50 , 50 ] ; let dp = new Array ( SIZE ) ; for ( let i = 0 ; i < SIZE ; i ++ ) { dp [ i ] = new Array ( N ) ; for ( let j = 0 ; j < N ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } document . write ( Math . min ( A [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 0 , dp ) , Math . min ( B [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 1 , dp ) , C [ 0 ] + minSum ( A , B , C , 1 , SIZE - 1 , 2 , dp ) ) ) ) ;