Friday, January 6, 2023

[LeetCode] Find Greatest Common Divisor of Array

Problem: Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Example:

Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.
The largest number in nums is 10.
The greatest common divisor of 2 and 10 is 2.
Input: nums = [7,5,6,8,3]
Output: 1
Explanation:
The smallest number in nums is 3.
The largest number in nums is 8.
The greatest common divisor of 3 and 8 is 1.
Input: nums = [3,3]
Output: 3
Explanation:
The smallest number in nums is 3.
The largest number in nums is 3.
The greatest common divisor of 3 and 3 is 3.


Approach: Nothing much to discuss. Just we need to find the min and max number of the array and then we need to calculate the GCD of min and max.


Implementation in C#:

    public int FindGCD(int[] nums)
    {
        int min = int.MaxValue;
        int max = int.MinValue;
        foreach (int num in nums)
        {
            min = min > num ? num : min;
            max = max < num ? num : max;
        }
        return this.GCD(max, min);
    }

    private int GCD(int a, int b)
    {
        while (b != 0)
        {
            int rem = a % b;
            a = b;
            b = rem;
        }
        return a;
    }

Complexity: O(n)

No comments:

Post a Comment