Minimum Cost to Split an Array
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] , then trimmed [1,2,3,3,3,4,4]) = [3,3,3,4,4]. The importance value of this subarray will be $k + 5$.
Return the minimum possible cost of a split of nums .
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,1,2,1,3,3], k = 2 Output: 8 Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6. The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits.
Example 2:
Input: nums = [1,2,1,2,1], k = 2 Output: 6 Explanation: We split nums to have two subarrays: [1,2], [1,2,1]. The importance value of [1,2] is 2 + (0) = 2. The importance value of [1,2,1] is 2 + (2) = 4. The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits.
Example 3:
Input: nums = [1,2,1,2,1], k = 5 Output: 10 Explanation: We split nums to have one subarray: [1,2,1,2,1]. The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10. The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.
Constraints:
- $1 \leq \text{nums.length} \leq 1000$
- $0 \leq \text{nums}[i] < text{nums.length}$
- $1 \leq k \leq {10}^9$
解题思路
md新年第一天就崩,打个lc周赛第三题wa了$4$发,最后一题搁这罚坐了一个小时都没做出来。
一开始想的是区间dp的做法,但时间复杂度是$O(n^3)$的。然后又想了个$O(n^2)$的分治,wa了也不知道哪里出了问题。
看了眼别人的代码用线性dp就自己写出来了,比赛的时候就是没想到。
定义状态$f(i)$表示所有将前$i$个位置划分成子数组的方案的最小代价,根据划分的最后一个子数组$[j, i]$来划分集合,因此状态转移方程为$\min\limits_{1 \leq j \leq i} \{ {f(j-1) + k + s_j} \}$,其中$s_j$表示区间$[j, i]$中的代价。
AC代码如下,时间复杂度为$O(n^2)$:
1 class Solution { 2 public: 3 int minCost(vector<int>& nums, int k) { 4 int n = nums.size(); 5 vector<int> f(n + 1, 0x3f3f3f3f); 6 f[0] = 0; 7 for (int i = 1; i <= n; i++) { 8 vector<int> cnt(n + 1); 9 int s = 0; 10 for (int j = i; j; j--) { 11 if (++cnt[nums[j - 1]] == 2) s += 2; 12 else if (cnt[nums[j - 1]] > 2) s++; 13 f[i] = min(f[i], f[j - 1] + k + s); 14 } 15 } 16 return f[n]; 17 } 18 };标签:cost,nums,importance,value,Minimum,split,subarray,Array,Split From: https://www.cnblogs.com/onlyblues/p/17064376.html