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
< ? php function maxSumPairWithDifferenceLessThanK ( $ arr , $ N , $ k ) { $ maxSum = 0 ; sort ( $ arr ) ; for ( $ i = $ N - 1 ; $ i > 0 ; -- $ i ) { if ( $ arr [ $ i ] - $ arr [ $ i - 1 ] < $ k ) { $ maxSum += $ arr [ $ i ] ; $ maxSum += $ arr [ $ i - 1 ] ; -- $ i ; } } return $ maxSum ; } $ arr = array ( 3 , 5 , 10 , 15 , 17 , 12 , 9 ) ; $ N = sizeof ( $ arr ) ; $ K = 4 ; echo maxSumPairWithDifferenceLessThanK ( $ arr , $ N , $ K ) ; ? >