
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum sum of pairs with specific difference in C++
In this tutorial, we will be discussing a program to find maximum sum of pairs with specific difference.
For this we will be provided with an array containing integers and a value K. Our task is to pair elements having difference less than K and finally find the maximum sum of the elements in disjoint sets.
Example
#include <bits/stdc++.h> using namespace std; //returning maximum sum of disjoint pairs int maxSumPairWithDifferenceLessThanK(int arr[], int N, int K){ sort(arr, arr+N); int dp[N]; dp[0] = 0; for (int i = 1; i < N; i++) { dp[i] = dp[i-1]; if (arr[i] - arr[i-1] < K) { if (i >= 2) dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]); else dp[i] = max(dp[i], arr[i] + arr[i-1]); } } return dp[N - 1]; } int main() { int arr[] = {3, 5, 10, 15, 17, 12, 9}; int N = sizeof(arr)/sizeof(int); int K = 4; cout << maxSumPairWithDifferenceLessThanK(arr, N, K); return 0; }
Output
62
- Related Articles
- Maximum sum of pairs with specific difference C++ program
- Number of pairs with maximum sum in C++
- Python Program to print a specific number of rows with Maximum Sum
- Maximum count of pairs which generate the same sum in C++
- Find Maximum difference between tuple pairs in Python
- Maximum sum of difference of adjacent elements in C++
- Print all the sum pairs which occur maximum number of times in C++
- Count pairs with given sum in C++
- Maximum sum of absolute difference of any permutation in C++
- Program to find two pairs of numbers where difference between sum of these pairs are minimized in python
- Maximum Length Chain of Pairs
- Print all pairs with given sum in C++
- Maximum Length Chain of Pairs in C++
- Subset with maximum sum in JavaScript
- Program to find sum of contiguous sublist with maximum sum in Python

Advertisements