Maximum length subarray with LCM equal to product in C++


Suppose we have an array A. We have to find the maximum length of the subarray, whose LCM is the same as the product of the elements of that subarray. If that kind of subarray is not found, then return -1. Suppose array is {6, 10, 21}, then the length is 2, as the subarray {10, 21} is there, whose LCM is 210, and the product is also 210.

The approach is straight forward. We have to check every possible subarray of length greater or equals to 2. If the subarray is satisfying the condition, then update the answer as a maximum of answer and length of sub-array.

Example

 Live Demo

#include <iostream>
using namespace std;
int gcd(int a, int b) {
   if (b == 0)
      return a;
   return gcd(b, a % b);
}
int maxLengthLCMSubarray(int arr[], int n) {
   int len = -1;
   for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
         long long lcm = 1LL * arr[i];
         long long product = 1LL * arr[i];
         for (int k = i + 1; k <= j; k++) {
            lcm = (((arr[k] * lcm)) / (gcd(arr[k], lcm)));
            product = product * arr[k];
         }
         if (lcm == product) {
            len = max(len, j - i + 1);
         }
      }
   }
   return len;
}
int main() {
   int arr[] = {8, 2, 6, 10, 13, 21, 7};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Maximum Length: " << maxLengthLCMSubarray(arr, n);
}

Output

Maximum Length: 3

Updated on: 21-Oct-2019

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements