Minimum distance to visit given K points on X | Java 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 java . util . * ; class solution { static int MinDistK ( int arr [ ] , int N , int K ) { int res = Integer . MAX_VALUE ; int dist = 0 ; for ( int 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 ; } public static void main ( String args [ ] ) { int K = 3 ; int arr [ ] = { - 30 , - 10 , 10 , 20 , 50 } ; int N = arr . length ; System . out . println ( MinDistK ( arr , N , K ) ) ; } }