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

PythonServer Side ProgrammingProgramming

Suppose we have an array A of n different numbers and another positive integer K, we have to find the longest sub-sequence in the array having Least Common Multiple (LCM) at most K. After than return the LCM and the length of the sub-sequence, following the indexes (starting from 0) of the elements of the obtained sub-sequence. Otherwise, return -1.

So, if the input is like A = [3, 4, 5, 6], K = 20, then the output will be LCM = 12, Length = 3, Indexes = [0,1,3]

To solve this, we will follow these steps −

  • n := size of A

  • my_dict := a map

  • for i in range 0 to n, do

    • my_dict[A[i]] := my_dict[A[i]] + 1

  • count := an array of size (k + 1) fill with 0

  • for each key in my_dict, do

    • if key <= k, then

      • i := 1

      • while key * i <= k, do

        • count[key * i] := count[key * i] + my_dict[key]

        • i := i + 1

    • otherwise,

      • come out from the loop

  • lcm := 0, size := 0

  • for i in range 1 to k + 1, do

    • if count[i] > size, then

      • size := count[i]

      • lcm := i

  • if lcm is same as 0, then

    • return -1

  • otherwise,

    • display lcm and size

    • for i in range 0 to n, do

      • if lcm mod A[i] is same as 0, then

        • display i

Example 

Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
def get_seq(A,k):
   n = len(A)
   my_dict = defaultdict(lambda:0)
   for i in range(0, n):
      my_dict[A[i]] += 1
   count = [0] * (k + 1)
   for key in my_dict:
      if key <= k:
         i = 1
         while key * i <= k:
            count[key * i] += my_dict[key]
            i += 1
      else:
         break
   lcm = 0
   size = 0
   for i in range(1, k + 1):
      if count[i] > size:
         size = count[i]
         lcm = i
   if lcm == 0:
      print(-1)
   else:
      print("LCM = {0}, Length = {1}".format(lcm, size))
      print("Index values: ", end = "")
      for i in range(0, n):
         if lcm % A[i] == 0:
            print(i, end = " ")

k = 20
A = [3, 4, 5, 6]
get_seq(A,k)

Input

[3, 4, 5, 6] , 20

Output

LCM = 12, Length = 3 Index values: 0 1 3
raja
Updated on 20-Aug-2020 07:49:33

Advertisements