Skip to main content

Maximum Subarray With Equal Products | Problem Explanation and Solution Approach

 In this blog post, we will discuss an intriguing problem from LeetCode Weekly Contest 431: "Maximum Subarray With Equal Products." We will break down the problem statement, understand the logic behind the solution, and explore a working implementation in C++.


Problem Statement

You are given an array of positive integers nums.

An array arr is called product equivalent if:

prod(arr)=lcm(arr)×gcd(arr)\text{prod(arr)} = \text{lcm(arr)} \times \text{gcd(arr)}

Where:

  1. prod(arr): The product of all elements in arr.
  2. gcd(arr): The greatest common divisor of all elements in arr.
  3. lcm(arr): The least common multiple of all elements in arr.

Your task is to return the length of the longest product equivalent subarray in nums.

A subarray is defined as a contiguous non-empty sequence of elements within an array.


Examples

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].
For this subarray:

  • Product = 1 * 2 * 1 * 1 * 1 = 2
  • GCD = 1
  • LCM = 2 Since prod = gcd * lcm, the subarray is valid, and its length is 5.

Example 2:

Input: nums = [2, 3, 4, 5, 6]
Output: 3
Explanation:
The longest product equivalent subarray is [3, 4, 5].
For this subarray:

  • Product = 3 * 4 * 5 = 60
  • GCD = 1
  • LCM = 60 Since prod = gcd * lcm, the subarray is valid, and its length is 3.

Example 3:

Input: nums = [1, 2, 3, 1, 4, 5, 1]
Output: 5
Explanation:
The longest product equivalent subarray is [2, 3, 1, 4, 5].
For this subarray:

  • Product = 120
  • GCD = 1
  • LCM = 120 Since prod = gcd * lcm, the subarray is valid, and its length is 5.

Constraints

  • 2nums.length1002 \leq \text{nums.length} \leq 100
  • 1nums[i]101 \leq \text{nums[i]} \leq 10

Solution Approach

This problem involves three mathematical concepts:

  1. Product (prod): Multiplying all elements in a subarray.
  2. Greatest Common Divisor (gcd): The largest integer that divides all elements of a subarray.
  3. Least Common Multiple (lcm): The smallest integer that is a multiple of all elements in a subarray.

The condition prod(arr) == lcm(arr) * gcd(arr) simplifies into a computational problem where we need to calculate the GCD and LCM iteratively for each subarray while avoiding overflow issues.


Steps to Solve

  1. Iterate Through All Subarrays:

    • Start with each index ii as the starting point of a subarray.
    • Extend the subarray to index jj and calculate the product, GCD, and LCM dynamically.
  2. Check the Condition:

    • For each subarray, check if prod(arr)=gcd(arr)×lcm(arr)\text{prod(arr)} = \text{gcd(arr)} \times \text{lcm(arr)}. If true, update the maximum subarray length.
  3. Prevent Overflow:

    • Since the product of the elements can grow exponentially, ensure the product does not exceed the limits of a 64-bit integer.
  4. Optimize Calculations:

    • Use the formula LCM(a,b)=a×bGCD(a,b)\text{LCM}(a, b) = \frac{a \times b}{\text{GCD}(a, b)} to calculate LCM efficiently.

C++ Code Implementation

Here’s the complete C++ code for solving the problem:

class Solution
{
public:
    int maxLength(vector<int> &nums)
    {
        int n = nums.size();
        int maxLength = 0;
        for (int i = 0; i < n; ++i)
        {
            long long prod = 1;
            int currentGCD = 0;
            long long currentLCM = 1;

            for (int j = i; j < n; ++j)
            {
                if (prod > LLONG_MAX / nums[j])
                    break;
                prod *= nums[j];
                currentGCD = (j == i) ? nums[j] : gcd(currentGCD, nums[j]);
                currentLCM = (j == i) ? nums[j] : (currentLCM / gcd(currentLCM, nums[j])) * nums[j];

                if (prod == currentGCD * currentLCM)
                {
                    maxLength = max(maxLength, j - i + 1);
                }
            }
        }
        return maxLength;
    }
};


Key Points

  1. GCD and LCM Calculation:

    • GCD is calculated using the built-in gcd function in C++.
    • LCM is calculated using the formula: LCM(a,b)=a×bGCD(a,b)\text{LCM}(a, b) = \frac{a \times b}{\text{GCD}(a, b)}
  2. Overflow Prevention:

    • If the product exceeds the maximum limit of a 64-bit integer (LLONG_MAX), break the loop.
  3. Time Complexity:

    • The algorithm runs in O(n2)O(n^2), where nn is the length of the array. For each subarray, GCD and LCM are calculated efficiently.
  4. Space Complexity:

    • The solution uses only scalar variables, resulting in O(1)O(1) additional space.

Example Walkthrough

Input: nums = [1, 2, 1, 2, 1, 1, 1]

  • Subarray [1, 2, 1, 1, 1] satisfies the condition.
  • Length = 5.

Input: nums = [2, 3, 4, 5, 6]

  • Subarray [3, 4, 5] satisfies the condition.
  • Length = 3.

Input: nums = [1, 2, 3, 1, 4, 5, 1]

  • Subarray [2, 3, 1, 4, 5] satisfies the condition.
  • Length = 5.

Popular posts from this blog

Top 10 Beginner-Friendly LeetCode Questions and Their Solutions

If you're new to solving coding problems on LeetCode, it can feel overwhelming. Where do you start? Which problems are suitable for beginners? Don’t worry! In this blog post, I’ll guide you through   10 beginner-friendly LeetCode questions   that are perfect for getting started on your coding journey. These problems will help you build confidence, improve your problem-solving skills, and lay a solid foundation in data structures and algorithms. Why Start with Beginner-Friendly Problems? Before diving into advanced topics like dynamic programming or graph theory, it’s essential to: Build a strong foundation in basic programming concepts. Understand how to approach a coding problem methodically. Gain familiarity with LeetCode’s platform and its problem structure. The following problems are simple yet impactful, designed to introduce you to common techniques like loops, arrays, strings, and basic math operations. 10 Beginner-Friendly LeetCode Problems 1.  Two Sum (Easy) Prob...

Maximum Difference Between Even and Odd Frequency | LeetCode

We are given a string consisting of lowercase English letters. Our task is to find the maximum difference between the frequency of two characters in the string such that: One of the characters has an even frequency . The other character has an odd frequency . The difference is calculated as:  odd_frequency - even_frequency We need to return the maximum possible difference between the odd and even frequencies. Example Walkthrough Let's take a couple of examples to better understand the problem: Example 1: Input:  s = "aaaaabbc" Frequencies: 'a' → 5 (odd) 'b' → 2 (even) 'c' → 1 (odd) Here, the maximum odd frequency is 5 (for 'a') and the maximum even frequency is 2 (for 'b'). Therefore, the result is: maxOdd - maxEven = 5 - 2 = 3 Example 2: Input:  s = "abcabcab" Frequencies: 'a' → 3 (odd) 'b' → 2 (even) 'c' → 2 (even) The maximum odd frequency is 3 (for 'a') and the maximum even fr...

Count Mentions Per User | Leetcode | Problem Explanation and Solution Approaches

Tracking mentions in messages is a common task in communication-based applications. This blog post breaks down a complex problem, "Count Mentions Per User," and walks through how to solve it efficiently with a clear understanding of all rules and constraints. Problem Statement You are given: An integer numberOfUsers representing the total number of users. An array events where each element is of size n x 3 and describes either a "MESSAGE" or an "OFFLINE" event. Each event can be one of the following types: MESSAGE Event : ["MESSAGE", "timestamp", "mentions_string"] Indicates that users are mentioned in a message at a specific timestamp. The mentions_string can contain: id<number> : Mentions a specific user (e.g., id0 , id1 ). ALL : Mentions all users (online or offline). HERE : Mentions only users who are online at the time. OFFLINE Event : ["OFFLINE", "timestamp", "id<number>"] In...