Maximum sum of pairs that are at least K distance apart in an array | java program for the above approach ; Function to find the largest sum pair that are K distant apart ; Stores the prefix maximum array ; Base Case ; Traverse the array and update the maximum value upto index i ; Stores the maximum sum of pairs ; Iterate over the range [ K , N ] ; Find the maximum value of the sum of valid pairs ; Return the resultant sum ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int getMaxPairSum ( int [ ] arr , int N , int K ) { int [ ] preMax = new int [ N ] ; preMax [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { preMax [ i ] = Math . max ( preMax [ i - 1 ] , arr [ i ] ) ; } int res = Integer . MIN_VALUE ; for ( int i = K ; i < N ; i ++ ) { res = Math . max ( res , arr [ i ] + preMax [ i - K ] ) ; } return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 8 , 6 , 3 } ; int K = 3 ; int N = arr . length ; System . out . print ( getMaxPairSum ( arr , N , K ) ) ; } }