Minimum distance to visit given K points on X | Function to find the minimum distance travelled to visit K polet ; Stores minimum distance travelled to visit K polet ; Stores distance travelled to visit polets ; 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
function MinDistK ( arr , N , K ) { let res = Number . MAX_VALUE ; let dist = 0 ; for ( let i = 0 ; i <= ( N - K ) ; i ++ ) { if ( arr [ i ] >= 0 && arr [ i + K - 1 ] >= 0 ) { dist = Math . max ( arr [ i ] , arr [ i + K - 1 ] ) ; } else { dist = Math . abs ( arr [ i ] ) + Math . abs ( arr [ i + K - 1 ] ) + Math . min ( Math . abs ( arr [ i ] ) , Math . abs ( arr [ i + K - 1 ] ) ) ; } res = Math . min ( res , dist ) ; } return res ; } let K = 3 ; let arr = [ - 30 , - 10 , 10 , 20 , 50 ] ; let N = arr . length ; document . write ( MinDistK ( arr , N , K ) ) ;