Divide an Array Into Subarrays With Minimum Cost I (LeetCode 3010): Solution and Explanation
Cut an array into three contiguous parts, where each part costs its first element, and return the smallest possible total cost.
Intuition
The first part always begins at index 0, so nums[0] is paid no matter how you cut.
The second and third parts begin at the two cut points. Any two indices i < j with i >= 1 give a valid split: [0..i-1], [i..j-1], [j..n-1].
So the choice is just which two elements of nums[1..] become part heads. To minimize the sum, pick the two smallest values there.
Their order in the array does not matter, because whichever comes first becomes the second part's head and the other becomes the third's.
Approach: Two smallest after index 0
- Set
firstandsecondto a value larger than any element. - For each
xinnums[1:]: ifx < first, movefirstintosecondand setfirst = x. - Otherwise, if
x < second, setsecond = x. - Return
nums[0] + first + second.
Step-by-step example
nums = [1,2,3,12]
- nums[0] = 1 is always paid.
- x = 2 becomes first. x = 3 is not below 2 but is below second, so second = 3.
- x = 12 is not below second, so nothing changes.
- Cut before index 1 and index 2 to get [1], [2], [3,12]. Return 1 + 2 + 3 = 6.
Code: Python, Java, C++
1class Solution:
2 def minimumCost(self, nums: List[int]) -> int:
3 first = second = 10**9
4 for x in nums[1:]:
5 if x < first:
6 second = first
7 first = x
8 elif x < second:
9 second = x
10 return nums[0] + first + second1class Solution {
2 public int minimumCost(int[] nums) {
3 int first = Integer.MAX_VALUE;
4 int second = Integer.MAX_VALUE;
5 for (int i = 1; i < nums.length; i++) {
6 int x = nums[i];
7 if (x < first) {
8 second = first;
9 first = x;
10 } else if (x < second) {
11 second = x;
12 }
13 }
14 return nums[0] + first + second;
15 }
16}1class Solution {
2public:
3 int minimumCost(vector<int>& nums) {
4 int first = INT_MAX;
5 int second = INT_MAX;
6 for (int i = 1; i < (int)nums.size(); i++) {
7 int x = nums[i];
8 if (x < first) {
9 second = first;
10 first = x;
11 } else if (x < second) {
12 second = x;
13 }
14 }
15 return nums[0] + first + second;
16 }
17};Time and space complexity
O(n)
One pass over nums[1..] with constant work per element.
O(1)
Only the two smallest values are stored.
Other approaches
Sort the tail (time O(n log n), space O(n))
Sort nums[1:] and add its first two elements to nums[0]. Short, but it pays for a sort.
Try every pair of cuts (time O(n^2), space O(1))
Loop over all i < j and take the minimum of nums[0] + nums[i] + nums[j]. Fine for n <= 50 but quadratic.
Common mistakes
- Including nums[0] when looking for the two smallest values. It is already paid, and it cannot also be a cut point.
- Using
x <= firstand losing a duplicate. With [10,3,1,1] both 1s must count, so equal values must still reachsecond. - Forgetting to move the old
firstintosecondwhen a new minimum arrives. - Thinking the two cuts must be in increasing value order. Only their positions matter, and any two distinct positions work.
Frequently asked questions
Why is any pair of indices a valid split?
For 1 <= i < j <= n - 1, the parts [0..i-1], [i..j-1] and [j..n-1] are all non-empty and cover the array.
What if the two smallest values are equal?
That is fine. They sit at different indices, so both can be part heads, as in [10,3,1,1] with answer 12.
What changes in the harder version of this problem?
Version II asks for k parts and limits how far apart the cuts may be, which needs a sliding window with ordered sets.