Pair with largest sum which is less than K in the array | CPP program for the above approach ; Function to find max sum less than k ; Sort the array ; While l is less than r ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( vector < int > arr , int k ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int n = arr . size ( ) , l = 0 , r = n - 1 , ans = 0 ; while ( l < r ) { if ( arr [ l ] + arr [ r ] < k ) { ans = max ( ans , arr [ l ] + arr [ r ] ) ; l ++ ; } else { r -- ; } } return ans ; } int main ( ) { vector < int > A = { 20 , 10 , 30 , 100 , 110 } ; int k = 85 ; cout << maxSum ( A , k ) << endl ; }