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;
}
相关推荐
飞Link5 小时前
什么是 PX4?一文了解 PX4 在空地协同中的作用
算法·无人机
一去不复返的通信er12 小时前
力扣-图论-岛屿数量
算法·leetcode·图论
程序 代码狂人14 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
HDU-Dade15 小时前
【校招笔试真题】简要介绍 Self-Attention 的前沿算法
人工智能·算法
Xin77016 小时前
LeetCode 79. 单词搜索(DFS 回溯法)
leetcode
Zwawa16 小时前
编译器工具链:GCC、Clang、MSVC、ICC、armclang
c语言·嵌入式·编译器
学逆向的16 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
水饺编程17 小时前
第2章:Linux 基础,exit 命令
linux·c语言·汇编
小郎君65817 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
邵奈一18 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法