Minimum distance to visit given K points on X | C # 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
using System ; class GFG { static int MinDistK ( int [ ] arr , int N , int K ) { int res = Int32 . MaxValue ; 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 ( ) { int K = 3 ; int [ ] arr = { - 30 , - 10 , 10 , 20 , 50 } ; int N = arr . Length ; Console . WriteLine ( MinDistK ( arr , N , K ) ) ; } }