Check If It Is a Good Array in C++

Suppose we have an array called nums of positive integers. We have to select some subset of nums, then multiply each element by an integer and add all these numbers. The array will be a good array if we can get a sum of 1 from the array by any possible subset and multiplicand.

We have to check whether the array is good or not.

So, if the input is like [12,23,7,5], then the output will be True, this is because If we take numbers 5, 7, then 5*3 + 7*(-2) = 1

To solve this, we will follow these steps −

  • g := nums[0]

  • for initialize i := 1, when i < size of nums, update (increase i by 1), do −

    • g := gcd of g and nums[i]

  • return true when g is 1

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int gcd(int a, int b){
      return !b ? a : gcd(b, a % b);
   bool isGoodArray(vector<int>& nums){
      int g = nums[0];
      for (int i = 1; i < nums.size(); i++)
      g = gcd(g, nums[i]);
      return g == 1;
   Solution ob;
   vector<int> v = {12,23,7,5};
   cout << (ob.isGoodArray(v));