Untitled

mail@pastecode.io avatar
unknown
java
10 days ago
1.6 kB
3
Indexable
Never
import java.util.*;

public class FemaleCodebreaker {

    // Function to calculate the GCD of two numbers
    public static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    // Function to find the maximum possible GCD and the corresponding maximum possible length of the subarray
    public static int[] gcdArrays(int[] arr) {
        int n = arr.length;
        int maxGCD = 0;
        int maxLength = 0;

        // Loop through all possible subarrays
        for (int i = 0; i < n; i++) {
            int currentGCD = arr[i];
            // Iterate over all possible subarrays starting at i
            for (int j = i + 1; j < n; j++) {
                currentGCD = gcd(currentGCD, arr[j]);
                int length = j - i + 1;
                // Check if the current subarray GCD is greater or if the GCD is the same but the length is longer
                if (currentGCD > maxGCD || (currentGCD == maxGCD && length > maxLength)) {
                    maxGCD = currentGCD;
                    maxLength = length;
                }
            }
        }
        
        // Return an array with maxGCD and maxLength
        return new int[] { maxGCD, maxLength };
    }

    public static void main(String[] args) {
        // Example input
        int[] arr = { 6, 9, 3 };
        // Call the gcdArrays function
        int[] result = gcdArrays(arr);
        // Output the result
        System.out.println("Max GCD: " + result[0] + ", Max Length: " + result[1]);
    }
}
Leave a Comment