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

C++Server Side ProgrammingProgramming

<p style="">Suppose we have a set of integers. We have to find a number &lsquo;d&rsquo;, 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</p><p>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.</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/rA4OYepH" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">#include&lt;iostream&gt; #include&lt;unordered_map&gt; #include&lt;climits&gt; using namespace std; int findElementsInSet(int arr[], int n) { &nbsp; &nbsp;unordered_map&lt;int, pair&lt;int, int&gt; &gt; table; &nbsp; &nbsp;for (int i = 0; i &lt; n - 1; i++) &nbsp; &nbsp; &nbsp; for (int j = i + 1; j &lt; n; j++) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;table[arr[i] + arr[j]] = { i, j }; &nbsp; &nbsp; &nbsp; int d = INT_MIN; &nbsp; &nbsp; &nbsp; for (int i = 0; i &lt; n - 1; i++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (int j = i + 1; j &lt; n; j++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int abs_diff = abs(arr[i] - arr[j]); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (table.find(abs_diff) != table.end()) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;pair&lt;int, int&gt; p = table[abs_diff]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (p.first != i &amp;&amp; p.first != j &amp;&amp; p.second != i &amp;&amp; p.second != j) d = max(d, max(arr[i], arr[j])); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;return d; } int main() { &nbsp; &nbsp;int arr[] = { 2, 3, 5, 7, 12 }; &nbsp; &nbsp;int n = sizeof(arr) / sizeof(arr[0]); &nbsp; &nbsp;int res = findElementsInSet(arr, n); &nbsp; &nbsp;if (res == INT_MIN) &nbsp; &nbsp; &nbsp; cout &lt;&lt; &quot;Cannot find the value of d&quot;; &nbsp; &nbsp;else &nbsp; &nbsp; &nbsp; cout &lt;&lt; &quot;Max value of d is &quot; &lt;&lt; res; }</pre><h2>Output</h2><pre class="result notranslate">Max value of d is 12</pre>
raja
Updated on 19-Dec-2019 09:56:32

Advertisements