Maximum product of a triplet (subsequence of size 3) in array in C++

C++Server Side ProgrammingProgramming

<p>In this tutorial, we will be discussing a program to find maximum product of a triplet (subsequence of size 3) in array.</p><p>For this we will be provided with an array of integers. Our task is to find the triplet of elements in that array with the maximum product</p><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;bits/stdc++.h&gt; using namespace std; //finding the maximum product int maxProduct(int arr[], int n){ &nbsp; &nbsp;if (n &lt; 3) &nbsp; &nbsp; &nbsp; return -1; &nbsp; &nbsp;int max_product = INT_MIN; &nbsp; &nbsp;for (int i = 0; i &lt; n - 2; i++) &nbsp; &nbsp; &nbsp; for (int j = i + 1; j &lt; n - 1; j++) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for (int k = j + 1; k &lt; n; k++) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max_product = max(max_product, arr[i] * arr[j] * arr[k]); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return max_product; } int main() { &nbsp; &nbsp;int arr[] = { 10, 3, 5, 6, 20 }; &nbsp; &nbsp;int n = sizeof(arr) / sizeof(arr[0]); &nbsp; &nbsp;int max = maxProduct(arr, n); &nbsp; &nbsp;if (max == -1) &nbsp; &nbsp; &nbsp; cout &lt;&lt; &quot;No Triplet Exists&quot;; &nbsp; &nbsp;else &nbsp; &nbsp; &nbsp; cout &lt;&lt; &quot;Maximum product is &quot; &lt;&lt; max; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">Maximum product is 1200</pre>
Updated on 09-Sep-2020 12:57:09