Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find pair with maximum GCD in an array
Next article icon

Longest sub-array with maximum GCD

Last Updated : 16 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of positive integers, 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: 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:

This method's temporal complexity is O(n^3), where n is the length of the input array, making it inefficient for large inputs. This is because each sub-array's GCD was calculated using nested loops that generated all of the sub-arrays.

Follow the steps:

  • Generate all sub-arrays
  • Calculate GCD for each sub-array
  • Check for maximum GCD value, and update the maximum gcd and maximum length accordingly.
  • Return the maximum length

Below is the implementation of the above approach:  

C++
#include <iostream> #include <algorithm> #include <vector> using namespace std;  // Function to calculate the greatest common divisor (GCD) of two numbers int gcd(int a, int b) {     while (b) {         a %= b;         swap(a, b); // Swapping values to continue the process     }     return a; // Return the GCD }  // Function to find the length of the longest sub-array with maximum GCD value (naive approach) int longestSubarrayNaive(vector<int>& arr) {     int n = arr.size(); // Length of the input array     int maxLength = 0; // Initialize the maximum length of sub-array       int maxGcd=0;     // Nested loops to generate all possible sub-arrays     for (int i = 0; i < n; ++i) {         for (int j = i; j < n; ++j) {             int subarrayGcd = arr[i]; // Initialize GCD value with the first element of the sub-array                          // Loop to calculate GCD of the sub-array elements             for (int k = i + 1; k <= j; ++k) {                 subarrayGcd = gcd(subarrayGcd, arr[k]); // Update GCD value iteratively             }                                      if (subarrayGcd > maxGcd) {                 maxLength = j - i + 1; // Update the maximum length if condition satisfies                   maxGcd=subarrayGcd;             }           else if(subarrayGcd == maxGcd)           {             maxLength = max(maxLength, j - i + 1);           }         }     }      return maxLength; // Return the length of the longest sub-array with maximum GCD }  int main() {     vector<int> arr1 = {1, 2, 2};     vector<int> arr2 = {3, 3, 3, 3};      // Example usage     cout << "Longest sub-array length for arr1: " << longestSubarrayNaive(arr1) << endl; // Output: 2     cout << "Longest sub-array length for arr2: " << longestSubarrayNaive(arr2) << endl; // Output: 4      return 0; } 
Java
import java.util.Arrays;  public class Main {     static int gcd(int a, int b) {         while (b != 0) {             int temp = b;             b = a % b;             a = temp;         }         return a;     }      static int longestSubarrayNaive(int[] arr) {         int n = arr.length;         int maxLength = 0;          for (int i = 0; i < n; i++) {             for (int j = i; j < n; j++) {                 int subarrayGcd = arr[i];                 for (int k = i + 1; k <= j; k++) {                     subarrayGcd = gcd(subarrayGcd, arr[k]);                 }                 if (subarrayGcd == Arrays.stream(arr, i, j + 1).max().getAsInt()) {                     maxLength = Math.max(maxLength, j - i + 1);                 }             }         }          return maxLength;     }      public static void main(String[] args) {         int[] arr1 = { 1, 2, 2 };         int[] arr2 = { 3, 3, 3, 3 };          System.out.println("Longest sub-array length for arr1: " + longestSubarrayNaive(arr1)); // Output: 2         System.out.println("Longest sub-array length for arr2: " + longestSubarrayNaive(arr2)); // Output: 4     } } 
Python
# Function to calculate the greatest common divisor (GCD) of two numbers def gcd(a, b):     while b:         a, b = b, a % b     return a  # Function to find the length of the longest sub-array with maximum GCD value (naive approach) def longest_subarray_naive(arr):     n = len(arr)  # Length of the input array     max_length = 0  # Initialize the maximum length of sub-array      # Nested loops to generate all possible sub-arrays     for i in range(n):         for j in range(i, n):             subarray = arr[i:j+1]  # Generate sub-array from index i to j (inclusive)             subarray_gcd = subarray[0]  # Initialize GCD value with the first element of the sub-array                          # Loop to calculate GCD of the sub-array elements             for k in range(1, len(subarray)):                 subarray_gcd = gcd(subarray_gcd, subarray[k])  # Update GCD value iteratively                          # Check if the GCD of the sub-array equals the maximum element of the sub-array             if subarray_gcd == max(subarray):                 max_length = max(max_length, len(subarray))  # Update the maximum length if condition satisfies      return max_length  # Return the length of the longest sub-array with maximum GCD  # Example usage arr1 = [1, 2, 2] arr2 = [3, 3, 3, 3]  print("Longest sub-array length for arr1:", longest_subarray_naive(arr1))  # Output: 2 print("Longest sub-array length for arr2:", longest_subarray_naive(arr2))  # Output: 4 
JavaScript
function gcd(a, b) {     while (b !== 0) {         const temp = b;         b = a % b;         a = temp;     }     return a; }  function longestSubarrayNaive(arr) {     const n = arr.length;     let maxLength = 0;      for (let i = 0; i < n; i++) {         for (let j = i; j < n; j++) {             let subarrayGcd = arr[i];             for (let k = i + 1; k <= j; k++) {                 subarrayGcd = gcd(subarrayGcd, arr[k]);             }             if (subarrayGcd === Math.max(...arr.slice(i, j + 1))) {                 maxLength = Math.max(maxLength, j - i + 1);             }         }     }      return maxLength; }  const arr1 = [1, 2, 2]; const arr2 = [3, 3, 3, 3];  console.log("Longest sub-array length for arr1:", longestSubarrayNaive(arr1)); // Output: 2 console.log("Longest sub-array length for arr2:", longestSubarrayNaive(arr2)); // Output: 4 

Output
Longest sub-array length for arr1: 2 Longest sub-array length for arr2: 4 


Time Complexity : O(n^3), where n is the length of the input array.

Auxilary Space: O(1)

Optimal 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 a single traversal of the input array.

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 = *max_element(arr, arr+n);           int ans = 0, count = 0;      for (int i = 0; i < n; i++) {         if (arr[i] == x) {             count++;             ans = max(ans, count);         }         else              count = 0;     }      return ans; }  // Driver code int main() {     int arr[] = { 1, 2, 2 };     int n = sizeof(arr) / sizeof(int);      cout << findLength(arr, n);      return 0; } 
Java
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]);                  int ans = 0, count = 0;          for (int i = 0; i < n; i++) {             if (arr[i] == x) {                 count++;                 ans = Math.max(ans, count);             } else {                 count = 0;             }         }          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));     } } 
Python
# 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          # To store current count     count = 0      for a in arr:         if (a == x):             count += 1              ans = max(ans, count)               else :             count = 0         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]);               int ans = 0, count = 0;         for (int i = 0; i < n; i++) {             if (arr[i] == x) {                 count++;                 ans = Math.Max(ans, count);             }             else                 count = 0;         }         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
// 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     let x = 0;      // Finding the maximum element     for (let i = 0; i < n; i++)         x = Math.max(x, arr[i]);      let ans = 0, count = 0;     for (let i = 0; i < n; i++) {         if (arr[i] == x) {             count++;             ans = Math.max(ans, count);         }         else             count = 0;     }      return ans; }  // Driver code var arr = [1, 2, 2 ]; var n = arr.length;  console.log( findLength(arr, n)); 

Output
2

Time Complexity: O(n)

Auxiliary Space: O(1)

Related Topic: Subarrays, Subsequences, and Subsets in Array


Next Article
Find pair with maximum GCD in an array

D

DivyanshuShekhar1
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
  • GCD-LCM
  • subarray
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Longest Sub-array with maximum average value
    Given an array arr[] of n integers. The task is to find the maximum length of the sub-array which has the maximum average value (average of the elements of the sub-array). [Tex] [/Tex]Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Outpu
    6 min read
  • Longest sub-sequence with maximum GCD
    Given an array arr[] of length N, the task is to find the length of the longest sub-sequence with the maximum possible GCD.Examples: Input: arr[] = {2, 1, 2} Output: 2 {2}, {2} and {2, 2} are the subsequences with the maximum possible GCD.Input: arr[] = {1, 2, 3} Output: 1 {3} is the required subseq
    4 min read
  • Length of longest sub-array with maximum arithmetic mean.
    Given an array of n-elements find the longest sub-array with the greatest arithmetic mean. The length of the sub-array must be greater than 1 and the mean should be calculated as an integer only.Examples: Input : arr[] = {3, 2, 1, 2} Output : 2 sub-array 3, 2 has greatest arithmetic mean Input :arr[
    5 min read
  • Find pair with maximum GCD in an array
    We are given an array of positive integers. Find the pair in array with maximum GCD.Examples: Input : arr[] : { 1 2 3 4 5 }Output : 2Explanation : Pair {2, 4} has GCD 2 which is highest. Other pairs have a GCD of 1.Input : arr[] : { 2 3 4 8 8 11 12 }Output : 8Explanation : Pair {8, 8} has GCD 8 whic
    15+ min read
  • Longest subarray having maximum sum
    Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
    12 min read
  • Maximum length of a sub-array with ugly numbers
    Given an array arr[] of N elements (0 ? arr[i] ? 1000). The task is to find the maximum length of the sub-array that contains only ugly numbers. Ugly numbers are numbers whose only prime factors are 2, 3, or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ..... shows the first few ugly numbers.
    8 min read
  • Pair with maximum GCD from two arrays
    Given two arrays of n integers with values of the array being small (values never exceed a small number say 100). Find the pair(x, y) which has maximum gcd. x and y cannot be of the same array. If multiple pairs have the same gcd, then consider the pair which has the maximum sum. Examples: Input : a
    15+ min read
  • Longest Subarrays having each Array element as the maximum
    Given an array arr[] of length N, the task is to find the longest subarray for each array element arr[i], which contains arr[i] as the maximum. Examples: Input: arr[] = {1, 2, 3, 0, 1} Output: 1 2 5 1 2 Explanation: The longest subarray having arr[0] as the largest is {1} The longest subarray having
    7 min read
  • Largest Subset with GCD 1
    Given n integers, we need to find size of the largest subset with GCD equal to 1. Input Constraint : n <= 10^5, A[i] <= 10^5 Examples: Input : A = {2, 3, 5}Output : 3Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.Input
    6 min read
  • Find a pair with maximum product in array of Integers
    Given an array with both +ive and -ive integers, return a pair with the highest product. Examples : Input: arr[] = {1, 4, 3, 6, 7, 0} Output: {6,7} Input: arr[] = {-1, -3, -4, 2, 0, -5} Output: {-4,-5} Recommended PracticeMaximum product of two numbersTry It! A Simple Solution is to consider every p
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences