[LeetCode] Minimum Subarrays in a Valid Split

2464. Minimum Subarrays in a Valid Split

You are given an integer array nums.

Splitting of an integer array nums into subarrays is valid if:

  • the greatest common divisor of the first and last elements of each subarray is greater than 1, and
  • each element of nums belongs to exactly one subarray.

Return the minimum number of subarrays in a valid subarray splitting of nums. If a valid subarray splitting is not possible, return -1.

Note that:

  • The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
  • A subarray is a contiguous non-empty part of an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
long long dp[1010];
class Solution {
long long helper(vector<int>& A, int pos) {
if(pos == A.size()) return 0;
if(dp[pos] != -1) return dp[pos];
long long& res = dp[pos] = INT_MAX;
for(int i = pos; i < A.size(); i++) {
int g = __gcd(A[i],A[pos]);
if(g == 1) continue;
res = min(res, 1 + helper(A,i+1));
}
return res;
}
public:
int validSubarraySplit(vector<int>& nums) {
memset(dp,-1,sizeof dp);
long long res = helper(nums, 0);
return res > nums.size() ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/21/PS/LeetCode/minimum-subarrays-in-a-valid-split/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.