Longest sub-sequence with maximum GCD
Last Updated :
23 Dec, 2022
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 subsequence.
Approach: The maximum possible GCD from the array will be equal to the value of the largest element in the array. Now, to maximize the length of the resulting subsequence, find the number of elements with a value equal to this largest value in the array, and the count of these elements is the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxLen( int * arr, int n)
{
int max_val = *max_element(arr, arr + n);
int freq = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == max_val)
freq++;
}
return freq;
}
int main()
{
int arr[] = { 3, 2, 2, 3, 3, 3 };
int n = sizeof (arr) / sizeof ( int );
cout << maxLen(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static int maxLen( int [] arr, int n)
{
int max_val = Arrays.stream(arr).max().getAsInt();
int freq = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] == max_val)
freq++;
}
return freq;
}
public static void main(String []args)
{
int arr[] = { 3 , 2 , 2 , 3 , 3 , 3 };
int n = arr.length;
System.out.println(maxLen(arr, n));
}
}
|
Python3
def maxLen(arr, n) :
max_val = max (arr);
freq = 0 ;
for i in range (n) :
if (arr[i] = = max_val) :
freq + = 1 ;
return freq;
if __name__ = = "__main__" :
arr = [ 3 , 2 , 2 , 3 , 3 , 3 ];
n = len (arr);
print (maxLen(arr, n));
|
C#
using System;
using System.Linq;
class GFG
{
static int maxLen( int [] arr, int n)
{
int max_val = arr.Max();
int freq = 0;
for ( int i = 0; i < n; i++)
{
if (arr[i] == max_val)
freq++;
}
return freq;
}
public static void Main(String []args)
{
int []arr = { 3, 2, 2, 3, 3, 3 };
int n = arr.Length;
Console.WriteLine(maxLen(arr, n));
}
}
|
Javascript
<script>
function maxLen(arr, n)
{
var max_val = arr.reduce((a,b) => Math.max(a,b));
var freq = 0;
for ( var i = 0; i < n; i++) {
if (arr[i] == max_val)
freq++;
}
return freq;
}
var arr = [3, 2, 2, 3, 3, 3];
var n = arr.length;
document.write( maxLen(arr, n));
</script>
|
Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...