LeetCode 1250: Check If It Is a Good Array
Problem Description
Explanation
To determine if an array is "good", we need to check if there exists a subset of the array elements such that the sum of the subset elements can be manipulated to equal 1. This can be done by using the fact that the GCD (greatest common divisor) of all the array elements should be 1. If the GCD of all elements is 1, it means we can find a linear combination of these elements to form 1.
Here is the algorithm:
- Compute the GCD of all elements in the array.
- If the GCD is 1, return True. Otherwise, return False.
Time complexity: O(n * log(max(nums))), where n is the number of elements in the array and max(nums) is the maximum value in the array. Space complexity: O(1)
Solutions
class Solution {
public boolean isGoodArray(int[] nums) {
int gcd = nums[0];
for (int num : nums) {
gcd = gcd(gcd, num);
if (gcd == 1) {
return true;
}
}
return gcd == 1;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
Loading editor...