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 ; Find the suffix array ; Iterate in the array ; Update 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 suffix_min [ ] = new int [ n ] ; suffix_min [ n - 1 ] = A [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_min [ i ] = Math . min ( suffix_min [ i + 1 ] , A [ i ] ) ; int min_sum = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + K < n ) min_sum = Math . min ( min_sum , A [ i ] + suffix_min [ i + K ] ) ; } System . out . println ( min_sum ) ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 2 ; findMinSum ( A , K ) ; } }