Find largest d in array such that a + b + c = d in C++

C++Server Side ProgrammingProgramming

Suppose we have a set of integers. We have to find a number ‘d’, where d = a + b + c, and we have to maximize (a + b + c), all a, b, c, and d are present in the set. The set will hold at least one element, and at max 1000 elements. Each element will be a finite number. If the set is {2, 3, 5, 7, 12}, then 12 is largest d. this can be represented by 2 + 3 + 7

To solve this problem, we can use the hashing technique. We will store the sum of all pairs of (a + b) in the hash table, then traverse through all pairs (c, d) and search (d - c) is present in the table or not. If one match is found, then make sure that no two elements are the same, and no same elements are considered twice.

Example

 Live Demo

#include<iostream>
#include<unordered_map>
#include<climits>
using namespace std;
int findElementsInSet(int arr[], int n) {
   unordered_map<int, pair<int, int> > table;
   for (int i = 0; i < n - 1; i++)
      for (int j = i + 1; j < n; j++)
         table[arr[i] + arr[j]] = { i, j };
      int d = INT_MIN;
      for (int i = 0; i < n - 1; i++) {
         for (int j = i + 1; j < n; j++) {
            int abs_diff = abs(arr[i] - arr[j]);
            if (table.find(abs_diff) != table.end()) {
               pair<int, int> p = table[abs_diff];
               if (p.first != i && p.first != j && p.second != i && p.second != j) d = max(d, max(arr[i], arr[j]));
            }
         }
      }
   return d;
}
int main() {
   int arr[] = { 2, 3, 5, 7, 12 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int res = findElementsInSet(arr, n);
   if (res == INT_MIN)
      cout << "Cannot find the value of d";
   else
      cout << "Max value of d is " << res;
}

Output

Max value of d is 12
raja
Published on 19-Dec-2019 09:54:36
Advertisements