You are given a whole number n. Write it as a sum of at least two positive whole numbers, then multiply those numbers together.
Return the largest product you can get this way.
Example 1
Input: n = 6 Output: 9 Why: 6 = 3 + 3, and 3 × 3 = 9
2 more examples and the constraints
Example 2
Input: n = 11 Output: 54 Why: 11 = 3 + 3 + 3 + 2, and 27 × 2 = 54
Example 3
Input: n = 3 Output: 2 Why: it must be split, and 1 + 2 is the best split
Constraints
- 2 ≤ n ≤ 58
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Bottom-up DPO(n²)
- Greedy: take 3sO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 58 | Verdict |
|---|---|---|---|
| Bottom-up DP | O(n²) | Passes; easy to justify | |
| Greedy: take 3s | O(n) | Best; needs the 3s argument |
n = the number to split.
Edge cases to test
- n = 2. The only split is 1 + 1, so the answer is 1, less than n.
- n = 3. 1 + 2 gives 2. Keeping 3 whole is not allowed at the top level.
- Remainder 1. n = 7 is 3 + 4 (12), never 3 + 3 + 1 (9).
- Largest n. 58 gives 3^18 × 4 = 1,549,681,956, which still fits in a 32-bit int.
Common mistakes
- Returning n for n = 2 or 3, forgetting that at least one split is required.
- Taking 3s while n > 3, which leaves a 1 and loses: 7 becomes 3 + 3 + 1.
- In the DP, using only
j × dp[i − j], which never keeps the rest whole and gets dp[4] wrong.
How to talk through it
- 1Clarify. Must there be at least two parts? Are all parts positive whole numbers? How large is n?
- 2Set up the DP. dp[i] is the best product for i; try every first part and keep or split the rest.
- 3Look for the pattern. Fill a few values: the best splits use 3s, with a 2 or a 4 at the end.
- 4Explain the greedy. Parts above 4 should be split, 1s are useless, and 3 + 3 beats 2 + 2 + 2.
- 5Test out loud. Run n = 2, 3, 4 and 7, and check the answers 1, 2, 4 and 12.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?