[LeetCode] Minimum Cost to Split an Array

2547. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int minCost(vector<int>& A, int k) {
vector<int> dp(A.size() + 1, INT_MAX);
dp[0] = 0;
for(int i = 0; i < A.size(); i++) {
int len = 0, cut = 0;
unordered_map<int,int> freq;
for(int j = i; j < A.size(); j++) {
len += 1;
++freq[A[j]];
if(freq[A[j]] == 1) cut += 1;
else if(freq[A[j]] == 2) cut -= 1;
dp[j+1] = min(dp[j+1], dp[i] + len - cut + k);
}
}
return dp.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/02/PS/LeetCode/minimum-cost-to-split-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.