Minimum Sum of a pair at least K distance apart from an Array | Java Program to implement the above approach ; Function to find the minimum sum of two elements that are atleast K distance apart ; Length of the array ; Iterate over the array ; Initialize the min value ; Iterate from i + k to N ; Find the minimum ; Update the minimum sum ; Print the answer ; Driver Code
import java . util . * ; class GFG { public static void findMinSum ( int A [ ] , int K ) { int n = A . length ; int minimum_sum = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int min = Integer . MAX_VALUE ; for ( int j = i + K ; j < n ; j ++ ) min = Math . min ( min , A [ j ] ) ; if ( min == Integer . MAX_VALUE ) continue ; minimum_sum = Math . min ( minimum_sum , A [ i ] + min ) ; } System . out . println ( minimum_sum ) ; } public static void main ( String [ ] args ) { int A [ ] = { 4 , 2 , 5 , 4 , 3 , 2 , 5 } ; int K = 3 ; findMinSum ( A , K ) ; } }