Minimum Cost to Split an Array
Minimum Cost to Split an Array
You are given an integer array nums and an integer .
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 .
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:
解题思路
md新年第一天就崩,打个lc周赛第三题wa了发,最后一题搁这罚坐了一个小时都没做出来。
一开始想的是区间dp的做法,但时间复杂度是的。然后又想了个的分治,wa了也不知道哪里出了问题。
看了眼别人的代码用线性dp就自己写出来了,比赛的时候就是没想到。
定义状态表示所有将前个位置划分成子数组的方案的最小代价,根据划分的最后一个子数组来划分集合,因此状态转移方程为,其中表示区间中的代价。
AC代码如下,时间复杂度为:
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 };
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17064376.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效