function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
fiona gentryfiona gentry 

Find Greatest Common Divisor of Array using Map Collection

Hi Folks,

Trying to solve the problem of Find Greatest Common Divisor of Array

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 1:

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.

Example 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.

Example 3:

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.

Here is code tried using Maps but no success ,any help is appreciated
 
public class GCDArray {
    public static List<String> greatestdiv(String input) {
        system.debug(input);
        List<String> inputList = input.split('');
        system.debug(inputList);
        Map<String,Integer> counts = new Map<String,Integer>();
        system.debug(counts);
        for(String s1:inputList) {
            counts.put(s1,0);
            system.debug(counts);
        }
        for(String s1:inputList) {
            counts.put(s1,counts.get(s1)+1);
        }
        system.debug(counts);
        String maxKey = counts.isEmpty()?null:new List<String>(counts.keyset())[0];
        system.debug(maxKey);
        for(String s1:counts.keySet()) {
            maxKey = counts.get(s1)>counts.get(maxKey)?s1:maxKey;
        }
        system.debug('The smallest number in array is'+ maxKey);
        system.debug(counts.get(maxKey));
        
        List<String> resultList = maxKey.split('');
        for( Integer S : counts.keySet() ){
            system.debug(S);
            resultList.add(S,counts.get(S));
            system.debug(resultList);
            
            
        }
        
        
        return resultList;      
    }
    
    
}

Regards,
Fiona
SwethaSwetha (Salesforce Developers) 
HI Fiona,
The link https://www.geeksforgeeks.org/gcd-two-array-numbers/ has the pseudo code based on which you will need to build the salesforce code snippet.

If this information helps, please mark the answer as best. Thank you