Skip to content
Related Articles

Related Articles

Longest sub-array with maximum GCD
  • Difficulty Level : Medium
  • Last Updated : 13 Jan, 2020
GeeksforGeeks - Summer Carnival Banner

Given an array arr[] of length N, the task is the find the length of the longest sub-array with maximum possible GCD value.

Examples:

Input: arr[] = {1, 2, 2}
Output: 2
Here all possible sub-arrays and there GCD’s are:
1) {1} -> 1
2) {2} -> 2
3) {2} -> 2
4) {1, 2} -> 1
5) {2, 2} -> 2
6) {1, 2, 3} -> 1
Here, the maximum GCD value is 2 and longest sub-array having GCD = 2 is {2, 2}.
Thus, the answer is {2, 2}.

Input: arr[] = {3, 3, 3, 3}
Output: 4

Naive approach: Generate all the possible sub-arrays and find the GCD of each of them individually in order to find the longest such sub-array. This approach will take O(N3) time to solve the problem.



Better approach: The maximum GCD value will always be equal to the largest number present in the array. Let’s say that the largest number present in the array is X. Now, the task is to find the largest sub-array having all X. The same can be done using the two-pointer approach. Below is the algorithm:

  • Find the largest number in the array. Let us call this number X.
  • Run a loop from i = 0
    • If arr[i] != X then increment i and continue.
    • Else initialise j = i.
    • While j < n and arr[j] = X, increment j.
    • Update the answer as ans = max(ans, j – i).
    • Update i as i = j.

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the length of
// the largest subarray with
// maximum possible GCD
int findLength(int* arr, int n)
{
    // To store the maximum number
    // present in the array
    int x = 0;
  
    // Finding the maximum element
    for (int i = 0; i < n; i++)
        x = max(x, arr[i]);
  
    // To store the final answer
    int ans = 0;
  
    // Two pointer
    for (int i = 0; i < n; i++) {
  
        if (arr[i] != x)
            continue;
  
        // Running a loop from j = i
        int j = i;
  
        // Condition for incrementing 'j'
        while (arr[j] == x)
            j++;
  
        // Updating the answer
        ans = max(ans, j - i);
    }
  
    return ans;
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 2 };
    int n = sizeof(arr) / sizeof(int);
  
    cout << findLength(arr, n);
  
    return 0;
}

Java




// Java implementation of the approach 
class GFG 
{
  
    // Function to return the length of 
    // the largest subarray with 
    // maximum possible GCD 
    static int findLength(int []arr, int n) 
    
        // To store the maximum number 
        // present in the array 
        int x = 0
      
        // Finding the maximum element 
        for (int i = 0; i < n; i++) 
            x = Math.max(x, arr[i]); 
      
        // To store the final answer 
        int ans = 0
      
        // Two pointer 
        for (int i = 0; i < n; i++) 
        
            if (arr[i] != x) 
                continue
      
            // Running a loop from j = i 
            int j = i; 
      
            // Condition for incrementing 'j' 
            while (arr[j] == x) 
            {
                j++; 
                if (j >= n )
                break;
            }
      
            // Updating the answer 
            ans = Math.max(ans, j - i); 
        
        return ans; 
    
      
    // Driver code 
    public static void main (String[] args)
    
        int arr[] = { 1, 2, 2 }; 
        int n = arr.length; 
      
        System.out.println(findLength(arr, n)); 
    
}
  
// This code is contributed by AnkitRai01

Python3




# Python3 implementation of the approach 
  
# Function to return the length of 
# the largest subarray with 
# maximum possible GCD 
def findLength(arr, n) :
  
    # To store the maximum number 
    # present in the array 
    x = 0
  
    # Finding the maximum element 
    for i in range(n) : 
        x = max(x, arr[i]); 
  
    # To store the final answer 
    ans = 0
  
    # Two pointer 
    for i in range(n) :
  
        if (arr[i] != x) :
            continue
  
        # Running a loop from j = i 
        j = i; 
  
        # Condition for incrementing 'j' 
        while (arr[j] == x) :
            j += 1
              
            if j >= n :
                break
  
        # Updating the answer 
        ans = max(ans, j - i); 
  
    return ans; 
  
# Driver code 
if __name__ == "__main__"
  
    arr = [ 1, 2, 2 ]; 
    n = len(arr); 
  
    print(findLength(arr, n)); 
      
# This code is contributed by AnkitRai01

C#




// C# implementation of the approach 
using System;
  
class GFG 
{
  
    // Function to return the length of 
    // the largest subarray with 
    // maximum possible GCD 
    static int findLength(int []arr, int n) 
    
        // To store the maximum number 
        // present in the array 
        int x = 0; 
      
        // Finding the maximum element 
        for (int i = 0; i < n; i++) 
            x = Math.Max(x, arr[i]); 
      
        // To store the final answer 
        int ans = 0; 
      
        // Two pointer 
        for (int i = 0; i < n; i++) 
        
            if (arr[i] != x) 
                continue
      
            // Running a loop from j = i 
            int j = i; 
      
            // Condition for incrementing 'j' 
            while (arr[j] == x) 
            {
                j++; 
                if (j >= n )
                break;
            }
      
            // Updating the answer 
            ans = Math.Max(ans, j - i); 
        
        return ans; 
    
      
    // Driver code 
    public static void Main ()
    
        int []arr = { 1, 2, 2 }; 
        int n = arr.Length; 
      
        Console.WriteLine(findLength(arr, n)); 
    
}
  
// This code is contributed by AnkitRai01
Output:
2

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :