Maximum sum of pairs that are at least K distance apart in an array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxPairSum ( int arr [ ] , int N , int K ) { int preMax [ N ] ; preMax [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { preMax [ i ] = max ( preMax [ i - 1 ] , arr [ i ] ) ; } int res = INT_MIN ; for ( int i = K ; i < N ; i ++ ) { res = max ( res , arr [ i ] + preMax [ i - K ] ) ; } return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 6 , 3 } ; int K = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMaxPairSum ( arr , N , K ) ; return 0 ; }