Find minimum sum such that one of every three consecutive elements is taken | A utility function to find minimum of 3 elements ; Returns minimum possible sum of elements such that an element out of every three consecutive elements is picked . ; Create a DP table to store results of subproblems . sum [ i ] is going to store minimum possible sum when arr [ i ] is part of the solution . ; When there are less than or equal to 3 elements ; Iterate through all other elements ; Driver code
function minimum ( a , b , c ) { return Math . min ( Math . min ( a , b ) , c ) ; } function findMinSum ( arr , n ) { var sum = Array ( n ) . fill ( 0 ) ; sum [ 0 ] = arr [ 0 ] ; sum [ 1 ] = arr [ 1 ] ; sum [ 2 ] = arr [ 2 ] ; for ( var i = 3 ; i < n ; i ++ ) sum [ i ] = arr [ i ] + minimum ( sum [ i - 3 ] , sum [ i - 2 ] , sum [ i - 1 ] ) ; return minimum ( sum [ n - 1 ] , sum [ n - 2 ] , sum [ n - 3 ] ) ; } var arr = [ 1 , 2 , 3 , 20 , 2 , 10 , 1 ] ; var n = arr . length ; document . write ( " " + findMinSum ( arr , n ) ) ;