Maximum sum of pairs with specific difference | Method to return maximum sum we can get by finding less than K difference pairs ; Sort elements to ensure every i and i - 1 is closest possible pair ; To get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; Case I : Diff of arr [ i ] and arr [ i - 1 ] is less then K , add to maxSum Case II : Diff between arr [ i ] and arr [ i - 1 ] is not less then K , move to next i since with sorting we know , arr [ i ] - arr [ i - 1 ] < arr [ i ] - arr [ i - 2 ] and so on . ; Assuming only positive numbers . ; When a match is found skip this pair ; Driver Code
def maxSumPairWithDifferenceLessThanK ( arr , N , k ) : NEW_LINE INDENT maxSum = 0 NEW_LINE arr . sort ( ) NEW_LINE i = N - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] < k ) : NEW_LINE INDENT maxSum += arr [ i ] NEW_LINE maxSum += arr [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return maxSum NEW_LINE DEDENT arr = [ 3 , 5 , 10 , 15 , 17 , 12 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE print ( maxSumPairWithDifferenceLessThanK ( arr , N , K ) ) NEW_LINE