Maximum sum of pairs that are at least K distance apart in an array | 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
function getMaxPairSum ( arr , N , K ) { var preMax = Array ( N ) ; preMax [ 0 ] = arr [ 0 ] ; for ( var i = 1 ; i < N ; i ++ ) { preMax [ i ] = Math . max ( preMax [ i - 1 ] , arr [ i ] ) ; } var res = - 1000000000 ; for ( var i = K ; i < N ; i ++ ) { res = Math . max ( res , arr [ i ] + preMax [ i - K ] ) ; } return res ; } var arr = [ 1 , 2 , 4 , 8 , 6 , 3 ] ; var K = 3 ; var N = arr . length ; document . write ( getMaxPairSum ( arr , N , K ) ) ;