Minimum absolute value of ( K – arr [ i ] ) for all possible values of K over the range [ 0 , N – 1 ] | Java program for the above approach ; Functinion to find the minimum absolute value of ( K - arr [ i ] ) for each possible value of K over the range [ 0 , N - 1 ] | ; Traverse the given array arr [ ] ; Stores the mininimum distance to any array element arr [ i ] ; Check if there is no safe position smaller than i ; Check if the current position is between two safe positions ; Take the minimum of two distances ; Check if the current index is a safe position ; Check if there is no safe position greater than i ; Print the minimum distance ; driver code
import java . io . * ; class GFG { public static void minimumDistance ( int arr [ ] , int N ) { int ind = 0 ; int prev = arr [ ind ] ; int s = arr . length ; for ( int i = 0 ; i < N ; i ++ ) { int distance = Integer . MAX_VALUE ; if ( i < arr [ 0 ] ) { distance = arr [ 0 ] - i ; } else if ( i >= prev && ind + 1 < s && i <= arr [ ind + 1 ] ) { distance = Math . min ( i - prev , arr [ ind + 1 ] - i ) ; if ( i == arr [ ind + 1 ] ) { distance = 0 ; prev = arr [ ind + 1 ] ; ind ++ ; } } else { distance = i - prev ; } System . out . print ( distance + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 5 ; int arr [ ] = { 0 , 4 } ; minimumDistance ( arr , N ) ; } }