Minimum Cost to Split into Ones Problem
#3857
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3857.
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 an integer denoting 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
2 1 1 2 1 1
Thus, the minimum total cost is 4 + 1 + 1 = 6.
Constraints:
1 <= n <= 500
Solution
Approach: Math
Splitting n into 1 and n - 1 costs 1 * (n - 1). Repeating this with the rest costs n - 2, then n - 3, and so on down to 1, so the total is (n - 1) + (n - 2) + ... + 1 = n(n - 1) / 2. This is the minimum: whatever the order of splits, every pair of the original n units ends up separated exactly once, and a split into parts a and b costs a * b, which is exactly the number of pairs it separates.
Complexity: O(1) time and O(1) space.
class Solution:
def minCost(self, n: int) -> int:
return n * (n - 1) // 2