Skip to main content

Minimum Cost to Split into Ones II - Solution & Explanation

MediumPremiumFree on FleetCode5 min read
Practice this problem

Problem Statement

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

Approach Overview

Problem Overview: You are given a binary structure (string or array) and need to split it into segments so that every resulting segment contains exactly one 1. Each split or transformation contributes to a total cost. The task is to compute the minimum cost required to isolate every 1 into its own segment.

Approach 1: Brute Force Partitioning (O(n^2) time, O(n) space)

Start by enumerating every possible split position and evaluate whether the resulting segments each contain exactly one 1. Use prefix counts to quickly determine how many 1s appear inside a candidate segment. A dynamic programming array dp[i] stores the minimum cost needed to process the prefix ending at index i. For each index, iterate backward to test all valid segment boundaries. This works because every segment must contain exactly one 1, but the nested scanning results in O(n^2) time.

Approach 2: Optimized DP with Prefix Tracking (O(n) time, O(n) space)

A key observation: valid segments are determined entirely by the positions of 1s. Instead of scanning all boundaries, track the indices where 1 appears and process the gaps between them. Maintain a running DP value representing the minimum cost to isolate all previous 1s. Each time you encounter another 1, compute the cost contribution from the zeros or characters between consecutive 1s. Because each index is processed once, the algorithm runs in linear time. Prefix counts or cumulative metrics help compute costs for gaps instantly.

Approach 3: Greedy Gap Processing (O(n) time, O(1) space)

When the cost structure depends only on the distance between consecutive 1s, the problem reduces to processing gaps between them. Iterate through the array and track the previous 1. Each new 1 determines a segment boundary and the gap contributes directly to the final cost. This avoids maintaining a full DP table and works when the cost of isolating segments depends purely on local transitions.

Recommended for interviews: The optimized DP or gap-based linear scan is the expected solution. Brute force shows you understand the segmentation constraint, but interviewers want to see the observation that only the relative positions of 1s matter. That insight converts a quadratic partition problem into a linear pass using prefix counts or simple index tracking. These patterns appear frequently in problems involving binary arrays, segmentation, or prefix statistics, especially with dynamic programming, arrays, and greedy algorithms.

Solution

To minimize the cost, we should first split n into 1 and n - 1, which costs n - 1; then split n - 1 into 1 and n - 2, which costs n - 2. Following this pattern, the total cost is accumulated as 1 + 2 + \dots + (n - 1) = \frac{n times (n - 1)}{2}.

The time complexity is O(1), and the space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force PartitioningO(n^2)O(n)Useful for understanding the segmentation constraint or when n is small
Dynamic Programming with Prefix CountsO(n)O(n)General optimized solution that scales to large inputs
Greedy Gap ProcessingO(n)O(1)Best when cost depends only on distance between consecutive ones

Video Solution

Minimum Cost to Split into Ones II • Owen Wu • 5 views views

Frequently Asked Questions

Is Minimum Cost to Split into Ones II easy or hard?
The problem is typically rated Medium because the brute-force idea is straightforward but inefficient. Recognizing that only the positions of '1's influence valid splits allows a linear-time solution, which is the key insight interviewers expect.
Minimum Cost to Split into Ones II Python/Java solution
Most implementations iterate through the binary array, record positions of '1's, and update the cost as gaps are processed. The logic translates directly to Python, Java, C++, or JavaScript because it relies on simple loops, counters, and optional DP arrays.
How to solve Minimum Cost to Split into Ones II in O(n)?
Track the previous position of a '1' while scanning the sequence. Each time a new '1' appears, compute the cost contribution from the gap between the current and previous '1'. Maintain a running minimum cost using dynamic programming or greedy accumulation, ensuring each element is processed exactly once.
What is the best approach for Minimum Cost to Split into Ones II?
The most efficient solution processes the positions of '1's and evaluates the gaps between them. By tracking these indices and updating the cost incrementally, you avoid testing every split boundary. This reduces the complexity from O(n^2) brute force to an O(n) dynamic programming or greedy scan.
Is Minimum Cost to Split into Ones II asked at Google/Amazon/Meta?
Problems involving binary segmentation, cost minimization, and prefix-based dynamic programming frequently appear in interviews at companies like Google, Amazon, and Meta. Variations often test whether candidates recognize patterns around processing positions of key elements such as '1's.
What data structure is used in Minimum Cost to Split into Ones II?
The solution primarily uses arrays and prefix tracking. A dynamic programming array or simple index variables track the previous '1' and accumulated cost. Some implementations also use prefix sums to quickly compute segment statistics.
What is the time complexity of Minimum Cost to Split into Ones II?
The optimal solution runs in O(n) time because the array or string is scanned once while tracking the positions of '1's. Each index contributes constant work. Space complexity ranges from O(1) to O(n) depending on whether a DP array or simple index tracking is used.

Ready to solve this problem?

Practice Minimum Cost to Split into Ones II with our built-in code editor and test cases.

Practice on FleetCode