Longest sub-sequence with maximum GCD
source link: https://www.geeksforgeeks.org/longest-sub-sequence-with-maximum-gcd/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
- Last Updated : 06 Nov, 2019
Given an array arr[] of length N, the task is to find the length of the longest sub-sequence with 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:
- Python3
filter_none
edit
close
play_arrow
link
brightness_4
code
// C++ implementation of the approach
#include <bits/stdc++.h>
using
namespace
std;
// Function to return the length
// of the largest subsequence with
// maximum possible GCD
int
maxLen(
int
* arr,
int
n)
{
// Maximum value from the array
int
max_val = *max_element(arr, arr + n);
// To store the frequency of the
// maximum element in the array
int
freq = 0;
for
(
int
i = 0; i < n; i++) {
// If current element is equal
// to the maximum element
if
(arr[i] == max_val)
freq++;
}
return
freq;
}
// Driver code
int
main()
{
int
arr[] = { 3, 2, 2, 3, 3, 3 };
int
n =
sizeof
(arr) /
sizeof
(
int
);
cout << maxLen(arr, n);
return
0;
}
4
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.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK