Minimize the sum of differences of consecutive elements after removing exactly K elements | Python3 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 ; driver function ; input values ; calling the required function ;
import numpy as np NEW_LINE N = 100 NEW_LINE INF = 1000000 NEW_LINE dp = np . zeros ( ( N , N ) ) ; NEW_LINE vis = np . zeros ( ( N , N ) ) ; NEW_LINE def findSum ( arr , n , k , l , r ) : NEW_LINE INDENT if ( ( l ) + ( n - 1 - r ) == k ) : NEW_LINE INDENT return arr [ r ] - arr [ l ] ; NEW_LINE DEDENT if ( vis [ l ] [ r ] ) : NEW_LINE INDENT return dp [ l ] [ r ] ; NEW_LINE DEDENT vis [ l ] [ r ] = 1 ; NEW_LINE dp [ l ] [ r ] = min ( findSum ( arr , n , k , l , r - 1 ) , findSum ( arr , n , k , l + 1 , r ) ) ; NEW_LINE return dp [ l ] [ r ] 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 , 0 , n - 1 ) ) ; NEW_LINE DEDENT