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
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
C++ Program for Longest Increasing Subsequence
Next article icon

Find the longest subsequence of an array having LCM at most K

Last Updated : 09 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N elements and a positive integer K. The task is to find the longest sub-sequence in the array having LCM (Least Common Multiple) at most K. Print the LCM and the length of the sub-sequence, following the indexes (starting from 0) of the elements of the obtained sub-sequence. Print -1 if it is not possible to do so.
Examples: 
 

Input: arr[] = {2, 3, 4, 5}, K = 14 
Output: 
LCM = 12, Length = 3 
Indexes = 0 1 2
Input: arr[] = {12, 33, 14, 52}, K = 4 
Output: -1 
 


 


Approach: Find all the unique elements of the array and their respective frequencies. Now the highest LCM that you are supposed to get is K. Suppose you have a number X such that 1 ? X ? K, obtain all the unique numbers from the array whom X is a multiple of and add their frequencies to numCount of X. The answer will be the number with highest numCount, let it be your LCM. Now, to obtain the indexes of the numbers of the sub-sequence, start traversing the array from the beginning and print the index i if LCM % arr[i] = 0.
Below is the implementation of the above approach: 
 

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // Function to find the longest subsequence // having LCM less than or equal to K void findSubsequence(int* arr, int n, int k) {      // Map to store unique elements     // and their frequencies     map<int, int> M;      // Update the frequencies     for (int i = 0; i < n; ++i)         ++M[arr[i]];      // Array to store the count of numbers whom     // 1 <= X <= K is a multiple of     int* numCount = new int[k + 1];      for (int i = 0; i <= k; ++i)         numCount[i] = 0;      // Check every unique element     for (auto p : M) {         if (p.first <= k) {              // Find all its multiples <= K             for (int i = 1;; ++i) {                 if (p.first * i > k)                     break;                  // Store its frequency                 numCount[p.first * i] += p.second;             }         }         else             break;     }      int lcm = 0, length = 0;      // Obtain the number having maximum count     for (int i = 1; i <= k; ++i) {         if (numCount[i] > length) {             length = numCount[i];             lcm = i;         }     }      // Condition to check if answer     // doesn't exist     if (lcm == 0)         cout << -1 << endl;     else {          // Print the answer         cout << "LCM = " << lcm              << ", Length = " << length << endl;          cout << "Indexes = ";         for (int i = 0; i < n; ++i)             if (lcm % arr[i] == 0)                 cout << i << " ";     } }  // Driver code int main() {      int k = 14;     int arr[] = { 2, 3, 4, 5 };     int n = sizeof(arr) / sizeof(arr[0]);      findSubsequence(arr, n, k);      return 0; } 
Java
// Java implementation of the approach import java.util.*;  class GFG {     // Function to find the longest subsequence     // having LCM less than or equal to K     static void findSubsequence(int []arr, int n, int k)     {              // Map to store unique elements         // and their frequencies         HashMap<Integer, Integer> M = new HashMap<Integer,Integer>();              // Update the frequencies         for (int i = 0; i < n; ++i)         {             if(M.containsKey(arr[i]))                 M.put(arr[i], M.get(arr[i])+1);             else                 M.put(arr[i], 1);         }                  // Array to store the count of numbers whom         // 1 <= X <= K is a multiple of         int [] numCount = new int[k + 1];              for (int i = 0; i <= k; ++i)             numCount[i] = 0;              Iterator<HashMap.Entry<Integer, Integer>> itr = M.entrySet().iterator();                   // Check every unique element         while(itr.hasNext())          {             HashMap.Entry<Integer, Integer> entry = itr.next();             if (entry.getKey() <= k)              {                      // Find all its multiples <= K                 for (int i = 1;; ++i)                  {                     if (entry.getKey() * i > k)                         break;                          // Store its frequency                     numCount[entry.getKey() * i] += entry.getValue();                 }             }             else                 break;         }              int lcm = 0, length = 0;              // Obtain the number having maximum count         for (int i = 1; i <= k; ++i)          {             if (numCount[i] > length)              {                 length = numCount[i];                 lcm = i;             }         }              // Condition to check if answer         // doesn't exist         if (lcm == 0)             System.out.println(-1);         else         {                  // Print the answer             System.out.println("LCM = " + lcm                 + " Length = " + length );                  System.out.print( "Indexes = ");             for (int i = 0; i < n; ++i)                 if (lcm % arr[i] == 0)                     System.out.print(i + " ");         }     }          // Driver code     public static void main (String[] args)      {              int k = 14;         int arr[] = { 2, 3, 4, 5 };         int n = arr.length;              findSubsequence(arr, n, k);     } }  // This code is contributed by ihritik 
Python3
# Python3 implementation of the approach from collections import defaultdict  # Function to find the longest subsequence # having LCM less than or equal to K def findSubsequence(arr, n, k):      # Map to store unique elements     # and their frequencies     M = defaultdict(lambda:0)      # Update the frequencies     for i in range(0, n):         M[arr[i]] += 1      # Array to store the count of numbers     # whom 1 <= X <= K is a multiple of     numCount = [0] * (k + 1)      # Check every unique element     for p in M:          if p <= k:               # Find all its multiples <= K             i = 1             while p * i <= k:                                   # Store its frequency                 numCount[p * i] += M[p]                 i += 1                  else:             break          lcm, length = 0, 0      # Obtain the number having maximum count     for i in range(1, k + 1):          if numCount[i] > length:              length = numCount[i]             lcm = i      # Condition to check if answer doesn't exist     if lcm == 0:         print(-1)     else:          # Print the answer         print("LCM = {0}, Length = {1}".format(lcm, length))          print("Indexes = ", end = "")         for i in range(0, n):             if lcm % arr[i] == 0:                 print(i, end = " ")      # Driver code if __name__ == "__main__":      k = 14     arr = [2, 3, 4, 5]      n = len(arr)      findSubsequence(arr, n, k)  # This code is contributed by Rituraj Jain 
C#
// C# implementation of the approach using System; using System.Collections.Generic;  class GFG {     // Function to find the longest subsequence     // having LCM less than or equal to K     static void findSubsequence(int []arr, int n, int k)     {              // Map to store unique elements         // and their frequencies         Dictionary<int, int> M = new Dictionary<int, int>();              // Update the frequencies         for (int i = 0; i < n; ++i)         {             if(M.ContainsKey(arr[i]))                 M[arr[i]]++;             else                 M[arr[i]] = 1;         }                  // Array to store the count of numbers whom         // 1 <= X <= K is a multiple of         int [] numCount = new int[k + 1];              for (int i = 0; i <= k; ++i)             numCount[i] = 0;              Dictionary<int, int>.KeyCollection keyColl = M.Keys;                  // Check every unique element         foreach(int key in keyColl)         {             if ( key <= k)              {                      // Find all its multiples <= K                 for (int i = 1;; ++i)                  {                     if (key * i > k)                         break;                          // Store its frequency                     numCount[key * i] += M[key];                 }             }             else                 break;         }              int lcm = 0, length = 0;              // Obtain the number having maximum count         for (int i = 1; i <= k; ++i)         {             if (numCount[i] > length)              {                 length = numCount[i];                 lcm = i;             }         }              // Condition to check if answer         // doesn't exist         if (lcm == 0)             Console.WriteLine(-1);         else          {                  // Print the answer             Console.WriteLine("LCM = " + lcm                 + " Length = " + length );                  Console.Write( "Indexes = ");             for (int i = 0; i < n; ++i)                 if (lcm % arr[i] == 0)                     Console.Write(i + " ");         }     }          // Driver code     public static void Main ()      {              int k = 14;         int []arr = { 2, 3, 4, 5 };         int n = arr.Length;              findSubsequence(arr, n, k);     } }  // This code is contributed by ihritik 
PHP
<?php // PHP implementation of the approach   // Function to find the longest subsequence  // having LCM less than or equal to K  function findSubsequence($arr, $n, $k)  {       // Map to store unique elements      // and their frequencies      $M = array();          for($i = 0; $i < $n; $i++)         $M[$arr[$i]] = 0 ;      // Update the frequencies      for ($i = 0; $i < $n; ++$i)          ++$M[$arr[$i]];       // Array to store the count of numbers      // whom 1 <= X <= K is a multiple of      $numCount = array();       for ($i = 0; $i <= $k; ++$i)          $numCount[$i] = 0;       // Check every unique element      foreach($M as $key => $value)     {         if ($key <= $k)         {               // Find all its multiples <= K              for ($i = 1;; ++$i)              {                  if ($key * $i > $k)                      break;                   // Store its frequency                  $numCount[$key * $i] += $value;              }          }          else             break;      }       $lcm = 0; $length = 0;       // Obtain the number having     // maximum count      for ($i = 1; $i <= $k; ++$i)      {          if ($numCount[$i] > $length)         {              $length = $numCount[$i];              $lcm = $i;          }      }       // Condition to check if answer      // doesn't exist      if ($lcm == 0)          echo -1 << "\n";      else      {           // Print the answer          echo "LCM = ", $lcm,               ", Length = ", $length, "\n";           echo "Indexes = ";          for ($i = 0; $i < $n; ++$i)              if ($lcm % $arr[$i] == 0)                  echo $i, " ";      }  }   // Driver code  $k = 14;  $arr = array( 2, 3, 4, 5 );  $n = count($arr);  findSubsequence($arr, $n, $k);   // This code is contributed by Ryuga ?> 
JavaScript
<script>  // JavaScript implementation of the approach  // Function to find the longest subsequence // having LCM less than or equal to K function findSubsequence(arr, n, k) {      // Map to store unique elements     // and their frequencies     let M = new Map();      // Update the frequencies     for (let i = 0; i < n; ++i) {         if (M.has(arr[i])) {             M.set(arr[i], M.get(arr[i]) + 1)         } else {             M.set(arr[i], 1)         }     }      // Array to store the count of numbers whom     // 1 <= X <= K is a multiple of     let numCount = new Array(k + 1);      for (let i = 0; i <= k; ++i)         numCount[i] = 0;      // Check every unique element     for (let p of M) {         if (p[0] <= k) {              // Find all its multiples <= K             for (let i = 1; ; ++i) {                 if (p[0] * i > k)                     break;                  // Store its frequency                 numCount[p[0] * i] += p[1];             }         }         else             break;     }      let lcm = 0, length = 0;      // Obtain the number having maximum count     for (let i = 1; i <= k; ++i) {         if (numCount[i] > length) {             length = numCount[i];             lcm = i;         }     }      // Condition to check if answer     // doesn't exist     if (lcm == 0)         document.write(-1 + "<br>");     else {          // Print the answer         document.write(         "LCM = " + lcm + ", Length = " + length + "<br>"         );          document.write("Indexes = ");         for (let i = 0; i < n; ++i)             if (lcm % arr[i] == 0)                 document.write(i + " ");     } }  // Driver code   let k = 14; let arr = [2, 3, 4, 5]; let n = arr.length;  findSubsequence(arr, n, k);   // This code is contributed by _saurabh_jaiswal  </script> 

Output: 
LCM = 12, Length = 3 Indexes = 0 1 2

 

Time Complexity: O(nlogn)

Auxiliary Space: O(n)


Next Article
C++ Program for Longest Increasing Subsequence

N

NaimishSingh
Improve
Article Tags :
  • Algorithms
  • Competitive Programming
  • C++ Programs
  • Data Structures
  • C++
  • DSA
Practice Tags :
  • CPP
  • Algorithms
  • Data Structures

Similar Reads

  • C++ Program for Longest Increasing Subsequence
    The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60,
    9 min read
  • C/C++ Program for Longest Increasing Subsequence
    Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = {3, 10, 2, 1, 20}Output: 3Explanation: The longest incre
    8 min read
  • Length of longest subarray whose sum is not divisible by integer K
    Given an array arr[] of size N and an integer k, our task is to find the length of longest subarray whose sum of elements is not divisible by k. If no such subarray exists then return -1.Examples: Input: arr[] = {8, 4, 3, 1, 5, 9, 2}, k = 2 Output: 5 Explanation: The subarray is {8, 4, 3, 1, 5} with
    10 min read
  • Length of longest subarray for each index in Array where element at that index is largest
    Given an array arr[] of size N, the task is to calculate, for i(0<=i<N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which
    15 min read
  • Longest subarray such that adjacent elements have at least one common digit | Set 1
    Given an array of N integers, write a program that prints the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common. Examples: Input : 12 23 45 43 36 97 Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common i
    11 min read
  • Length of longest common subarray for given N arrays
    Given a 2-D array array[][] containing N arrays, the task is to find the longest common subarray(LCS) among N arrays. Examples: Input: N = 3, array[][] = { { 0, 1, 2, 3, 4 }, { 2, 3, 4 }, { 4, 0, 1, 2, 3 } }Output: 2Explanation: The longest common subpath is {2, 3}. Input: N = 2, array[][] = {{0, 1,
    12 min read
  • C++ Program for Longest Common Subsequence
    LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So
    3 min read
  • Largest substring where all characters appear at least K times | Set 2
    Given a string str and an integer K, the task is to find the length of the longest sub-string S such that every character in S appears at least K times. Examples: Input: str = "aabbba", K = 3Output: 6 Explanation: In substring aabbba, each character repeats at least k times and its length is 6. Inpu
    7 min read
  • Number of subsequences of maximum length K containing no repeated elements
    Given an array arr[] of N elements and a positive integer K such that K ≤ N. The task is to find the number of subsequences of maximum length K i.e. subsequences of length 0, 1, 2, ..., K - 1, K that have all distinct elements. Examples: Input: arr[] = {2, 2, 3, 3, 5}, K = 2 Output: 14 All the valid
    15 min read
  • Product of all Subsequences of size K except the minimum and maximum Elements
    Given an array A[] containing N elements and an integer K. The task is to calculate the product of all elements of subsequences of size K except the minimum and the maximum elements for each subsequence. Note: Since the answer can be very large so print the final answer as mod of 109 + 7. Examples:
    12 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