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 ; Driver code ; input values ; calling the required function ;
def findSum ( arr , n , k ) : NEW_LINE INDENT ans = arr [ n - k - 1 ] - arr [ 0 ] ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT ans = min ( arr [ n - 1 - ( k - i ) ] - arr [ i ] , ans ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 100 , 120 , 140 ] ; NEW_LINE k = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findSum ( arr , n , k ) ) ; NEW_LINE DEDENT