Skip to content

Commit 33b9eab

Browse files
authored
Create minimum-subarrays-in-a-valid-split.cpp
1 parent 195406e commit 33b9eab

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n^2 * logr), r = max(nums)
2+
// Space: O(n)
3+
4+
// dp
5+
class Solution {
6+
public:
7+
int validSubarraySplit(vector<int>& nums) {
8+
static const int INF = numeric_limits<int>::max();
9+
10+
vector<int> dp(size(nums) + 1, INF); // dp[i]: min number of subarrays in nums[:i]
11+
dp[0] = 0;
12+
for (int i = 1; i <= size(nums); ++i) {
13+
for (int j = 0; j < i; ++j) {
14+
if (gcd(nums[j], nums[i - 1]) != 1) {
15+
if (dp[j] != INF) {
16+
dp[i] = min(dp[i], dp[j] + 1);
17+
}
18+
}
19+
}
20+
}
21+
return dp.back() != INF ? dp.back() : -1;
22+
}
23+
};

0 commit comments

Comments
 (0)