Program to find product of few numbers whose sum is given in Python

PythonServer Side ProgrammingProgramming

<p>Suppose we have a number n, we have to find two or more numbers such that their sum is equal to n, and the product of these numbers is maximized, we have to find the product.</p><p>So, if the input is like n = 12, then the output will be 81, as 3 + 3 + 3 + 3 = 12 and 3 * 3 * 3 * 3 = 81.</p><p>To solve this, we will follow these steps &minus;</p><ul class="list"><li><p>Define a function dp() . This will take n</p></li><li><p>if n is same as 0, then</p><ul class="list"><li><p>return 1</p></li></ul></li><li><p>ans := 0</p></li><li><p>for i in range 1 to n + 1, do</p><ul class="list"><li><p>ans := maximum of ans and (i * dp(n &minus; i))</p></li></ul></li><li><p>return ans</p></li><li><p>From the main method, do the following &minus;</p></li><li><p>return dp(n)</p></li></ul><p>Let us see the following implementation to get better understanding &minus;</p><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">class Solution: &nbsp; &nbsp;def solve(self, n): &nbsp; &nbsp; &nbsp; def dp(n): &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if n == 0: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 1 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ans = 0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for i in range(1, n + 1): &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ans = max(ans, i * dp(n - i)) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return ans &nbsp; &nbsp; &nbsp; return dp(n) ob1 = Solution() print(ob1.solve(12))</pre><h2>Input</h2><pre class="result notranslate">12</pre><h2>Output</h2><pre class="result notranslate">81</pre>
Updated on 21-Oct-2020 11:09:45