I am a solving programming question in Leetcode in which, given a number $n \in \mathbb{N}_{\geqslant 2}$, I have to find $(a_1, ..., a_k) \in \mathbb{N}^k$ such that $k \in \mathbb{N}$, $2 \leqslant k \leqslant n$, $\sum_{i=1}^{k} a_i = n$, and $\prod_{i=1}^{k} a_i$ is maximum.
More specifically, given a natural number $n$ greater than $1$, I have to split this number into $k$ natural numbers/partitions $(a_1, ..., a_k)$, where $k$ is greater than $1$ and less than or equals to $n$, the sum of all $a_i$s, for $i$ between $1$ and $k$, results in $n$, and the product of all $a_i$s is maximum.
Let me give you some examples:
- Example 1: With $n = 2$, the only partition we can have is $(1, 1)$, since $k \geqslant 2$.
- Example 2: With $n = 3$, the only partitions we can have are $(2, 1)$ or $(1, 2)$ (note that the partition values order does not matter), since they satisfy the stated conditions.
- Example 3: With $n = 7$, the partitions $(3, 4)$ and $(3, 2, 2)$ give the maximum product ($3 \times 2 \times 2 = 3 \times 4 = 12$), have a number of elements less than or equals to $n$ and greater than 1, and their values sum results in $n$.
- Example 4: With $n = 10$, the partitions $(3, 3, 2, 2)$ and $(3, 3, 4)$ give that maximum product ($3 \times 3 \times 2 \times 2 = 3 \times 3 \times 4 = 36$), and satisfy all the stated conditions.
Already exists good algorithms to solve this problem. However, there is one that is used to find the maximum product for this problem in $O(1)$ time complexity. The algorithm is as follows:
- if $n \leqslant 3$, then return $n - 1$;
- else if the remainder of $\frac{n}{3}$ is $0$, i.e., $0 \equiv n ($mod $3)$ ($n$ is divisible by $3$), then return $3^{\frac{n}{3}}$
- else if the remainder of $\frac{n}{3}$ is $1$, i.e., $1 \equiv n ($mod $3)$, then return $4 \times 3^{\frac{n}{3} - 1}$
- else if the remainder of $\frac{n}{3}$ is $2$, i.e., $2 \equiv n ($mod $3)$, then return $2 \times 3^{\frac{n}{3}}$
This algorithm is used in the programming community to solve this problem. There is an informal correctness proof for this algorithm (here) but irrespective of that I am not convinced (and even clueless and doubtful) why this works. Thence, I would like to know if anyone can see some concealed property in the natural numbers $\geqslant 4$ that permits to find the maximum product partition by leveraging its remainder of division by $3$, i.e., what is the motif of using division by $3$. If anyone has any understating regarding the algorithm or sees any flaw/bug in it, please let me know.
For more implementation details (here).
I am sorry if any clumsy notation makes mathematicians worrisome, but I am a computer scientist.
Very thank you.