See the original problem on HackerRank.
Herb puts Bjarne’s birthday present in a cuboid box. The dimensions of its edges are positive integers and the sum of its length
, height
, and width
is N
.
Input Format
A single integer, N
(the sum of the box’s length
, height
, and width
).
Constraints
\(3 \leq N \leq 10^3\)
Output Format
Print the maximum possible volume of the box.
Solutions
The product of edge lengths is maximized when the lenghts are as long as possible.That is, we have to evenly distribute the available lenght through the edges and then give the possible remainder two one or two edges (the remainder is at most 2 because we divde by 3).
We start by setting all edges to \(N/3\) and then we just distribute the remainder evenly:


The same can be implemented with reduce pattern:


In Rust we can explain it with enumerate, map, product:


The solution above is generalized on DIM
, the number of dimension. It is a
box, so the dimension is 3
. Due to this fact, we can write it with primitive
types and operations:


Note that Rust compiler produces exactly the same machine code for the two programs above. Here an x86_64 assembly code:

