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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinDistK ( int arr [ ] , int N , int K ) { int res = INT_MAX ; int dist = 0 ; for ( int i = 0 ; i <= ( N - K ) ; i ++ ) { if ( arr [ i ] >= 0 && arr [ i + K - 1 ] >= 0 ) { dist = max ( arr [ i ] , arr [ i + K - 1 ] ) ; } else { dist = abs ( arr [ i ] ) + abs ( arr [ i + K - 1 ] ) + min ( abs ( arr [ i ] ) , abs ( arr [ i + K - 1 ] ) ) ; } res = min ( res , dist ) ; } return res ; } int main ( ) { int K = 3 ; int arr [ ] = { -30 , -10 , 10 , 20 , 50 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MinDistK ( arr , N , K ) ; }