Minimize the sum of differences of consecutive elements after removing exactly K elements | function to find minimum sum ; variable to store final answer and initialising it with the values when 0 elements is removed from the left and K from the right . ; loop to simulate removal of elements ; removing i elements from the left and and K - i elements from the right and updating the answer correspondingly ; returning final answer ; input values ; callin the required function ;
function findSum ( arr , n , k ) { var ans = arr [ n - k - 1 ] - arr [ 0 ] ; for ( var i = 1 ; i <= k ; i ++ ) { ans = Math . min ( arr [ n - 1 - ( k - i ) ] - arr [ i ] , ans ) ; } return ans ; } var arr = [ 1 , 2 , 100 , 120 , 140 ] ; var k = 2 ; var n = arr . length ; document . write ( findSum ( arr , n , k ) ) ;