3958. Minimum Cost to Split into Ones II 🔒
题目描述
You are given an integer n.
In one operation, you may split an integer x into two positive integers a and b such that a + b = x.
The cost of this operation is a * b.
Return the minimum total cost required to split the integer n into n ones.
Example 1:
Input: n = 3
Output: 3
Explanation:
One optimal set of operations is:
x | a | b | a + b | a * b | Cost |
|---|---|---|---|---|---|
| 3 | 1 | 2 | 3 | 2 | 2 |
| 2 | 1 | 1 | 2 | 1 | 1 |
Thus, the minimum total cost is 2 + 1 = 3.
Example 2:
Input: n = 4
Output: 6
Explanation:
One optimal set of operations is:
x | a | b | a + b | a * b | Cost |
|---|---|---|---|---|---|
| 4 | 2 | 2 | 4 | 4 | 4 |
| 2 | 1 | 1 | 2 | 1 | 1 |
Thus, the minimum total cost is 4 + 1 + 1 = 6.
Constraints:
1 <= n <= 5 * 107
解法
方法一:数学
要使得成本最小,我们应该首先将 \(n\) 拆分成 \(1\) 和 \(n - 1\),所需成本为 \(n - 1\);然后将 \(n - 1\) 拆分成 \(1\) 和 \(n - 2\),所需成本为 \(n - 2\)。依此类推,得到总成本为 \(1 + 2 + \dots + (n - 1) = \frac{n \times (n - 1)}{2}\)。
时间复杂度 \(O(1)\),空间复杂度 \(O(1)\)。
1 2 3 | |
1 2 3 4 5 | |
1 2 3 4 5 6 | |
1 2 3 | |
1 2 3 | |