Minimum Cost to Split an Array - Problem
You are given an integer array nums and an integer k.
Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split.
Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed.
- For example,
trimmed([3,1,2,4,3,4]) = [3,4,3,4].
The importance value of a subarray is k + trimmed(subarray).length.
- For example, if a subarray is
[1,2,3,3,3,4,4], thentrimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4]. The importance value of this subarray will bek + 5.
Return the minimum possible cost of a split of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,2,2], k = 3
›
Output:
8
💡 Note:
Split into [1,2,3,2] and [2]. First subarray has trimmed([1,2,3,2]) = [2,2] with length 2, so cost = 3+2 = 5. Second subarray has trimmed([2]) = [] with length 0, so cost = 3+0 = 3. Total = 5+3 = 8.
Example 2 — All Duplicates
$
Input:
nums = [1,1,1,1], k = 2
›
Output:
6
💡 Note:
Keep as single array [1,1,1,1]. trimmed([1,1,1,1]) = [1,1,1,1] with length 4. Cost = 2+4 = 6. Any split would cost more since each subarray adds k=2.
Example 3 — All Unique
$
Input:
nums = [1,2,3,4], k = 1
›
Output:
4
💡 Note:
Best to split into individual elements: [1], [2], [3], [4]. Each has trimmed length 0, so each costs 1+0 = 1. Total = 1+1+1+1 = 4.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 1000
- 1 ≤ k ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
[1,2,3,2,2] with k=3
2
Try Split
Split into [1,2,3,2] and [2]
3
Calculate Cost
First: 3+2=5, Second: 3+0=3, Total: 8
Key Takeaway
🎯 Key Insight: Only elements that appear multiple times in a subarray contribute to its trimmed length and cost
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code