Minimum Cost to Split an Array

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:

  • 1nums.length1000
  • 0nums[i]<textnums.length
  • 1k109

 

解题思路

  md新年第一天就崩,打个lc周赛第三题wa了4发,最后一题搁这罚坐了一个小时都没做出来。

  一开始想的是区间dp的做法,但时间复杂度是O(n3)的。然后又想了个O(n2)的分治,wa了也不知道哪里出了问题。

  看了眼别人的代码用线性dp就自己写出来了,比赛的时候就是没想到。

  定义状态f(i)表示所有将前i个位置划分成子数组的方案的最小代价,根据划分的最后一个子数组[j,i]来划分集合,因此状态转移方程为min1ji{f(j1)+k+sj},其中sj表示区间[j,i]中的代价。

  AC代码如下,时间复杂度为O(n2)

复制代码
 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 };
复制代码
posted @   onlyblues  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
Web Analytics
点击右上角即可分享
微信分享提示