Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the longest subsequence of an array having LCM at most K in Python
Given an array of numbers and a positive integer K, we need to find the longest subsequence where the Least Common Multiple (LCM) is at most K. The function returns the LCM value, length of the subsequence, and indices of elements in the optimal subsequence.
Problem Understanding
For example, if we have array A = [3, 4, 5, 6] and K = 20, we need to find which combination of elements gives us the longest subsequence with LCM ? 20. The LCM of [3, 4, 6] is 12, which is ? 20, and this gives us the longest valid subsequence.
Algorithm Approach
The solution uses a frequency-based approach:
Count frequency of each element in the array
For each possible LCM value from 1 to K, count how many elements can divide it
Find the LCM value with maximum count of divisors
Return the result with corresponding indices
Implementation
from collections import defaultdict
def get_longest_subsequence(A, k):
n = len(A)
my_dict = defaultdict(lambda: 0)
# Count frequency of each element
for i in range(0, n):
my_dict[A[i]] += 1
# Count array to store number of elements that can divide each LCM
count = [0] * (k + 1)
# For each unique element, mark all its multiples up to k
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
# Find the LCM with maximum count
for i in range(1, k + 1):
if count[i] > size:
size = count[i]
lcm = i
if lcm == 0:
return -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=" ")
print() # New line for clean output
# Test the function
A = [3, 4, 5, 6]
k = 20
get_longest_subsequence(A, k)
LCM = 12, Length = 3 Index values: 0 1 3
How It Works
The algorithm works by finding which potential LCM value (from 1 to K) can be formed by the maximum number of elements from the array:
Frequency Count: Count occurrence of each element
Divisor Mapping: For each element, increment count for all its multiples up to K
Optimal LCM: Find the LCM value with maximum possible elements
Index Extraction: Find indices where LCM is divisible by array elements
Example Walkthrough
For A = [3, 4, 5, 6] and K = 20:
Element 3: contributes to LCMs 3, 6, 9, 12, 15, 18
Element 4: contributes to LCMs 4, 8, 12, 16, 20
Element 5: contributes to LCMs 5, 10, 15, 20
Element 6: contributes to LCMs 6, 12, 18
LCM = 12 has the maximum count (3 elements: 3, 4, 6), so it's our answer.
Conclusion
This algorithm efficiently finds the longest subsequence with LCM at most K using frequency counting and divisibility relationships. The time complexity is O(K log K) for the nested loops, making it suitable for moderate values of K.
