703338. Jay's Apples

Basic

Jay's Apples

Summary

Jay has a set of apples and wants to distribute them among his friends. He gives each friend an equal number of apples, but not necessarily the same type. The problem is to write a program that takes the total number of apples Jay has and the types of apples he has as input, and outputs the maximum possible number of friends Jay can give apples to.

Detailed Explanation

To solve this problem, we need to find the greatest common divisor (GCD) of all the apple counts. This is because if there are more than two people, then it's not possible for each person to have a different number of apples. We will use the Euclidean algorithm to calculate the GCD.

Here is the step-by-step breakdown:

  1. Initialize a variable result to store the GCD.
  2. Compare the counts of each type of apple with the current result.
  3. Update the result to be the smaller value between the current result and the count of the current type of apple.
  4. Repeat steps 2-3 until only one count remains, which is the GCD.

The time complexity for this algorithm is O(k), where k is the number of types of apples. The space complexity is constant, as we only need to store a few variables.

Optimized Solutions

Here are optimized solutions in different languages:

Java

View on GeeksforGeeks
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        long gcd = 1;
        for(int i=0; i<n; i++) {
            long a = scanner.nextLong();
            while(a > 1) {
                long b = a;
                a = b % gcd;
                if(a == 0)
                    gcd = b;
            }
        }
        System.out.println(gcd);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.