Problem
We are required to write a JavaScript function that takes in an Integer, num, as the first and the only argument.
Our function should break these integers into at least two chunks which when added gives the sum integer num and when multiplied gives maximum possible product. Finally, our function should return this maximum possible product.
For example, if the input to the function is −
const num = 10;
Then the output should be −
const output = 36;
Output Explanation:
Because 10 can be broken into 3 + 3 + 4 which when multiplied gives 36.
Example
The code for this will be −
const num = 10; const breakInt = (num = 2) => { const dp = new Array(num + 1).fill(0); dp[0] = 0; dp[1] = 1; for(let i = 2; i <= num; i++){ for(let j = 1; 2*j <= i; j++){ dp[i] = Math.max(dp[i], Math.max(j, dp[j]) * Math.max(i-j, dp[i-j]) ); }; }; return dp[num]; }; console.log(breakInt(num));
Output
And the output in the console will be −
36