Longest sub-array with maximum GCD
Last Updated :
16 Aug, 2024
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
OutputLongest 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));
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Topic: Subarrays, Subsequences, and Subsets in Array
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). Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Output: 2 {6} and
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
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
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
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^5Examples: 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
Length of longest subarray of length at least 2 with maximum GCD Given an array arr[] of length N, the task is the find the length of longest subarray of length at least 2 with maximum possible GCD value.Examples: Input: arr[] = {1, 2, 2} Output: 2 Explanation: Possible sub-arrays of size greater than 2 and there GCDâs are: 1) {1, 2} -> 1 2) {2, 2} -> 2 3)
7 min read
Maximum possible GCD for a pair of integers with sum N Given an integer N, the task is to find the maximum possible GCD of a pair of integers such that their sum is N. Examples : Input: N = 30 Output: 15 Explanation: GCD of (15, 15) is 15, which is the maximum possible GCD Input: N = 33 Output: 11 Explanation: GCD of (11, 22) is 11, which is the maximum
4 min read
Largest subarray with GCD one There is an array with n elements. Find length of the largest subarray having GCD equal to 1. If no subarray with GCD 1, then print -1. Examples : Input : 1 3 5 Output : 3 Input : 2 4 6 Output :-1 Recommended PracticeLargest subarray with GCD oneTry It! A simple solution is to consider every subarra
6 min read
Maximum length subarray with LCM equal to product Given an arr[], the task is to find the maximum length of the sub-array such that the LCM of the sub-array is equal to the product of numbers in the sub-array. If no valid sub-array exists, then print -1. Note: The length of the sub-array must be ? 2. Examples: Input: arr[] = { 6, 10, 21} Output: 2
15+ min read