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;
}
相关推荐
SuperByteMaster3 小时前
freertos 任务创建方式
c语言
CodeRecycle3 小时前
Python 自动配置 pip 支持库(通过 Windows Bat 脚本)
算法
liliangcsdn3 小时前
特质偏度因子的计算示例和分析
算法
susplus3 小时前
【传感器DS18B20】51单片机上实现温度采集
c语言·51单片机·ds18b20·温度采集
荆棘鸟智能4 小时前
无人机遥感图像实时拼接算法工程实践:从特征提取到全景融合的完整技术链路
算法·无人机
6Hzlia4 小时前
【Classic 150 刷题计划】 LeetCode 58. 最后一个单词的长度 | C++ 极简反向遍历与单变量状态机
算法
AgentMaster4 小时前
企业如何应用智能客服?5 个典型场景的技术架构与实施路径
大数据·算法
程曦曦5 小时前
MySQL 生产库误删 98 张表后的时间点恢复实战:从 binlog 解析到资金对账
linux·数据结构·其他·算法·ubuntu·运维开发
Logic1015 小时前
C语言/数据结构位运算题解:异或XOR找出流水线上的“独特零件编号“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质