
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Integer Break in C++
Suppose we have a positive integer n, we have to break it into the sum of at least two positive numbers and maximize the product of those integers. We have to find the maximum product we can get. So if the number is 10, then the answer will be 36, as 10 = 3 + 3 + 4, 3 * 3 * 4 = 36
To solve this, we will follow these steps −
Define a method solve(), this will take n, array dp and flag
if n is 0, then return 1
if dp[n] is not -1, then return dp[n]
end := n – 1 when flag is set, otherwise n
ret := 0
-
for i in range 1 to end
ret := max of ret and i* solve(n – i, dp, false)
set dp[n] := ret and return
From the main method, create an array dp of size n + 1 and fill this with – 1
return solve(n, dp)
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int solve(int n, vector <int>& dp, bool flag = true){ if(n == 0) return 1; if(dp[n] != -1) return dp[n]; int end = flag? n - 1: n; int ret = 0; for(int i = 1; i <= end; i++){ ret = max(ret, i * solve(n - i, dp, false)); } return dp[n] = ret; } int integerBreak(int n) { vector <int>dp(n + 1, -1); return solve(n, dp); } }; main(){ Solution ob; cout << (ob.integerBreak(10)); }
Input
10
Output
36