3336. Find the Number of Subsequences With Equal GCD
Description
You are given an integer array nums.
Your task is to find the number of pairs of non-empty (seq1, seq2) of nums that satisfy the following conditions:
- The subsequences
seq1andseq2are disjoint, meaning no index ofnumsis common between them. - The of the elements of
seq1is equal to the GCD of the elements ofseq2.
Return the total number of such pairs.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4]
Output: 10
Explanation:
The subsequence pairs which have the GCD of their elements equal to 1 are:
([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])([1, 2, 3, 4], [1, 2, 3, 4])
Example 2:
Input: nums = [10,20,30]
Output: 2
Explanation:
The subsequence pairs which have the GCD of their elements equal to 10 are:
([10, 20, 30], [10, 20, 30])([10, 20, 30], [10, 20, 30])
Example 3:
Input: nums = [1,1,1,1]
Output: 50
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 200
Solutions
Solution: Dynamic Programming
- Time complexity: O(n*Max(nums)2)
- Space complexity: O(n*Max(nums)2)
JavaScript
js
/**
* @param {number[]} nums
* @return {number}
*/
const subsequencePairCount = function (nums) {
const n = nums.length;
const MODULO = 10 ** 9 + 7;
const maxNum = Math.max(...nums);
const dp = Array.from({ length: n }, () => {
return new Array(maxNum + 1)
.fill('')
.map(_ => new Array(maxNum + 1).fill(-1));
});
const gcd = (a, b) => (b ? gcd(b, a % b) : a);
const getPairCount = (index, x, y) => {
if (index >= n) return x > 0 && x === y ? 1 : 0;
if (dp[index][x][y] !== -1) return dp[index][x][y];
const num = nums[index];
const skip = getPairCount(index + 1, x, y);
const pickX = getPairCount(index + 1, gcd(num, x), y);
const pickY = getPairCount(index + 1, x, gcd(num, y));
const result = (skip + pickX + pickY) % MODULO;
dp[index][x][y] = result;
return result;
};
return getPairCount(0, 0, 0);
};