Minimum distance to visit given K points on X | Python3 program to implement the above approach ; Function to find the minimum distance travelled to visit K point ; Stores minimum distance travelled to visit K point ; Stores distance travelled to visit points ; Traverse the array arr [ ] ; If arr [ i ] and arr [ i + K - 1 ] are positive ; Update dist ; Update dist ; Update res ; Driver Code ; Initial the array
import sys NEW_LINE def MinDistK ( arr , N , K ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE dist = 0 NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ i + K - 1 ] >= 0 ) : NEW_LINE INDENT dist = max ( arr [ i ] , arr [ i + K - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dist = ( abs ( arr [ i ] ) + abs ( arr [ i + K - 1 ] ) + min ( abs ( arr [ i ] ) , abs ( arr [ i + K - 1 ] ) ) ) NEW_LINE DEDENT res = min ( res , dist ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 3 NEW_LINE arr = [ - 30 , - 10 , 10 , 20 , 50 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinDistK ( arr , N , K ) ) NEW_LINE DEDENT