Minimize the sum of differences of consecutive elements after removing exactly K elements | Javascript implementation of the above approach . ; states of DP ; function to find minimum sum ; base - case ; if state is solved before , return ; marking the state as solved ; recurrence relation ; input values ; calling the required function ;
var N = 100 ; var INF = 1000000 ; var dp = Array . from ( Array ( N ) , ( ) => Array ( N ) ) ; var vis = Array . from ( Array ( N ) , ( ) => Array ( N ) ) ; function findSum ( arr , n , k , l , r ) { if ( ( l ) + ( n - 1 - r ) == k ) return arr [ r ] - arr [ l ] ; if ( vis [ l ] [ r ] ) return dp [ l ] [ r ] ; vis [ l ] [ r ] = 1 ; dp [ l ] [ r ] = Math . min ( findSum ( arr , n , k , l , r - 1 ) , findSum ( arr , n , k , l + 1 , r ) ) ; return dp [ l ] [ r ] ; } var arr = [ 1 , 2 , 100 , 120 , 140 ] ; var k = 2 ; var n = arr . length ; document . write ( findSum ( arr , n , k , 0 , n - 1 ) ) ;