Split \(n\) into at least two positives maximizing the product. Listing partitions is large. If the last part is \(j\), the rest is either kept whole or already optimal.
\(f[i]=\max_j \max(f[i-j]\cdot j,\,(i-j)\cdot j)\) with \(f[1]=1\). Fill by increasing \(i\); the answer is \(f[n]\). \(n\le 58\) allows \(O(n^2)\).
We define \(f[i]\) as the maximum product that can be obtained by splitting the positive integer \(i\), with an initial condition of \(f[1] = 1\). The answer is \(f[n]\).
Consider the last number \(j\) split from \(i\), where \(j \in [1, i)\). For the number \(j\) split from \(i\), there are two cases:
Split \(i\) into the sum of \(i - j\) and \(j\), without further splitting, where the product is \((i - j) \times j\);
Split \(i\) into the sum of \(i - j\) and \(j\), and continue splitting, where the product is \(f[i - j] \times j\).
Therefore, we can derive the state transition equation:
#define max(a, b) (((a) > (b)) ? (a) : (b))intintegerBreak(intn){int*f=(int*)malloc((n+1)*sizeof(int));f[1]=1;for(inti=2;i<=n;++i){f[i]=0;for(intj=1;j<i;++j){f[i]=max(f[i],max(f[i-j]*j,(i-j)*j));}}returnf[n];}
Solution 1: Mathematics
Thinking
Method 1 does not name the optimal parts. For \(n\ge 4\) use as many \(3\)s as possible; a remainder \(1\) becomes \(2+2\), a remainder \(2\) keeps an extra \(2\). For \(n<4\) the product is \(n-1\). Closed form in \(O(1)\).
When \(n < 4\), since the problem requires splitting into at least two integers, \(n - 1\) yields the maximum product. When \(n \geq 4\), we split into as many \(3\)s as possible. If the last segment remaining is \(4\), we split it into \(2 + 2\) for the maximum product.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).