Description
Maximum Subarray With Equal Products
EasyYou are given an array of positive integers nums.
An array arr is called product equivalent if prod(arr) == lcm(arr) * gcd(arr), where:
prod(arr)is the product of all elements ofarr.gcd(arr)is the GCD of all elements ofarr.lcm(arr)is the LCM of all elements ofarr.
Return the length of the longest product equivalent subarray of nums.
Example 1:
Input: nums = [1,2,1,2,1,1,1]
Output: 5
Explanation:
The longest product equivalent subarray is [1, 2, 1, 1, 1], where prod([1, 2, 1, 1, 1]) = 2, gcd([1, 2, 1, 1, 1]) = 1, and lcm([1, 2, 1, 1, 1]) = 2.
Example 2:
Input: nums = [2,3,4,5,6]
Output: 3
Explanation:
The longest product equivalent subarray is [3, 4, 5].
Example 3:
Input: nums = [1,2,3,1,4,5,1]
Output: 5
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 10
Solutions
Simplified everything down, still got below average performance. If this is an easy exercise, I can't imagine how many years of work experience juniors need before their first job.
/**
* @param {number[]} nums
* @return {number}
*/
var maxLength = function (nums) {
let max = 0;
for (let i = 0; i < nums.length; i++) {
let p = nums[i];
let l = nums[i];
let g = nums[i];
for (let j = i + 1; j < nums.length; j++) {
p *= nums[j];
l = lcm(l, nums[j]);
g = gcd(g, nums[j]);
if (p === l * g) {
max = Math.max(max, j - i + 1);
}
}
}
return max;
};
const gcd = (a, b) => {
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
};
const lcm = (a, b) => {
return (a / gcd(a, b)) * b;
};