Minimize cost to reach end of an array by two forward jumps or one backward jump in each move | Function to find the minimum cost to reach the end of an array ; Base Case : When N < 3 ; Store the results in table ; Initialize base cases ; Iterate over the range [ 2 , N - 2 ] to construct the dp array ; Handle case for the last index , i . e . N - 1 ; Print the answer ; Driver Code
def minCost ( arr , n ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT print ( arr [ 0 ] ) NEW_LINE return NEW_LINE DEDENT dp = [ 0 ] * n NEW_LINE dp [ 0 ] = arr [ 0 ] NEW_LINE dp [ 1 ] = dp [ 0 ] + arr [ 1 ] + arr [ 2 ] NEW_LINE for i in range ( 2 , n - 1 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 2 ] + arr [ i ] , dp [ i - 1 ] + arr [ i ] + arr [ i + 1 ] ) NEW_LINE DEDENT dp [ n - 1 ] = min ( dp [ n - 2 ] , dp [ n - 3 ] + arr [ n - 1 ] ) NEW_LINE print ( dp [ n - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 9 , 4 , 6 , 8 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE minCost ( arr , N ) NEW_LINE DEDENT