Monday, November 18, 2024
Google search engine
HomeData Modelling & AILongest sub-array with maximum GCD

Longest sub-array with maximum GCD

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

Examples:  

Input: arr[] = {1, 2, 2} 
Output:
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:

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 initialize 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


Javascript




<script>
  
// Javascript implementation of the approach
  
// Function to return the length of
// the largest subarray with
// maximum possible GCD
function findLength(arr, n)
{
    // To store the maximum number
    // present in the array
    var x = 0;
  
    // Finding the maximum element
    for (var i = 0; i < n; i++)
        x = Math.max(x, arr[i]);
  
    // To store the final answer
    var ans = 0;
  
    // Two pointer
    for (var i = 0; i < n; i++) {
  
        if (arr[i] != x)
            continue;
  
        // Running a loop from j = i
        var j = i;
  
        // Condition for incrementing 'j'
        while (arr[j] == x)
            j++;
  
        // Updating the answer
        ans = Math.max(ans, j - i);
    }
  
    return ans;
}
  
// Driver code
var arr = [1, 2, 2 ];
var n = arr.length;
  
document.write( findLength(arr, n));
  
</script>


Output: 

2

 

Time Complexity: O(n)

Auxiliary Space: O(1)

Related Topic: Subarrays, Subsequences, and Subsets in Array

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments