LeetCode //C - 1250. Check If It Is a Good Array

1250. Check If It Is a Good Array

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.

53 + 7(-2) = 1

Example 2:

Input: nums = 29,6,10

Output: true

Explanation: Pick numbers 29, 6 and 10.

291 + 6(-3) + 10*(-1) = 1

Example 3:

Input: nums = 3,6

Output: false

Constraints:
  • 1 <= nums.length <= 10^5
  • 1 <= numsi <= 10^9

From: LeetCode

Link: 1250. Check If It Is a Good Array


Solution:

Ideas:

by Bézout's identity, the array is good only when the GCD of all numbers is 1.

Code:
c 复制代码
#include <stdbool.h>

int gcd(int a, int b) {
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}

bool isGoodArray(int* nums, int numsSize) {
    int g = nums[0];

    for (int i = 1; i < numsSize; i++) {
        g = gcd(g, nums[i]);

        if (g == 1) {
            return true;
        }
    }

    return g == 1;
}
相关推荐
罗湖老棍子1 小时前
Biorhythms(信息学奥赛一本通- P1639)
算法·数论·裴蜀定理·扩展欧几里得·扩展中国剩余定理
奋发向前wcx6 小时前
CSP-J复赛模拟赛4 王晨旭补题 2026.10.5
算法
念何架构之路9 小时前
zap采样器与性能优化内幕
算法·性能优化·哈希算法
晒太羊的猫10 小时前
hot100动态规划刷题
算法·动态规划
weixin_5310946910 小时前
heap_4内存管理
java·开发语言·算法
余额瞒着我当琳10 小时前
红黑树的实现--红黑树的概念、规则、效率、结构、旋转、查找、验证
数据结构·c++·算法
程序员南飞10 小时前
win系统安装minio
java·数据结构·算法
青少儿编程课堂10 小时前
AC自动机多模式串匹配精讲:校园关键词巡检实战解析
c++·python·算法·bfs·信息学竞赛
longlongzihan11 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
waoooqwe11 小时前
问卷样本真实吗
大数据·数据库·算法·数据分析