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;
}
相关推荐
电科_银尘18 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习
文丑颜不良啊18 小时前
LeetCode3081~3100题目解析
java·leetcode
电科_银尘18 小时前
【大模型算法与工程 05】分类、回归与排序指标:怎样评价一个模型
算法·分类·回归
文丑颜不良啊1 天前
LeetCode2981~3000题目解析
java·leetcode
罗西的思考1 天前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(2)
人工智能·算法·机器学习
罗西的思考1 天前
【轻量化复刻大模型 / KIMI K3】Multi-Token Prediction(MTP / EAGLE-3)(1)
人工智能·算法·机器学习
武子康1 天前
H3-World 接入 Game Agent:谁来判断门真的打开了?
人工智能·算法·机器学习
文丑颜不良啊1 天前
LeetCode3001~3020题目解析
java·leetcode
Zwawa1 天前
陀螺仪数据为什么看起来总在动:零偏、噪声和零漂
c语言·单片机·嵌入式
武子康2 天前
H3-World 扩展跳跃与开门:新动作怎样进入训练数据?
大数据·人工智能·算法