comments | difficulty | edit_url | rating | source | tags | |||
---|---|---|---|---|---|---|---|---|
true |
Hard |
1983 |
Weekly Contest 161 Q4 |
|
Given an array nums
of positive integers. Your task is to select some subset of nums
, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1
from the array by any possible subset and multiplicand.
Return True
if the array is good otherwise return False
.
Example 1:
Input: nums = [12,5,7,23] Output: true Explanation: Pick numbers 5 and 7. 5*3 + 7*(-2) = 1
Example 2:
Input: nums = [29,6,10] Output: true Explanation: Pick numbers 29, 6 and 10. 29*1 + 6*(-3) + 10*(-1) = 1
Example 3:
Input: nums = [3,6] Output: false
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
First, consider the situation where we select two numbers. If the selected numbers are
According to Bézout's Identity, if
Therefore, we only need to determine whether there exist nums
. The necessary and sufficient condition for two numbers to be coprime is that their greatest common divisor is nums
, then the greatest common divisor of all numbers in the array nums
is also
So we transform the problem into: determining whether the greatest common divisor of all numbers in the array nums
is nums
and finding the greatest common divisor of all numbers in the array nums
.
The time complexity is nums
, and nums
.
class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
return reduce(gcd, nums) == 1
class Solution {
public boolean isGoodArray(int[] nums) {
int g = 0;
for (int x : nums) {
g = gcd(x, g);
}
return g == 1;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
class Solution {
public:
bool isGoodArray(vector<int>& nums) {
int g = 0;
for (int x : nums) {
g = gcd(x, g);
}
return g == 1;
}
};
func isGoodArray(nums []int) bool {
g := 0
for _, x := range nums {
g = gcd(x, g)
}
return g == 1
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}