Skip to main content
Back to problems
Leetcode
Medium
Arrays
Math
Number Theory
Maximum Subarray With Equal Products

Find the longest contiguous subarray whose element product equals the product of its length and its maximum element.

Acceptance 0%
Problem Statement

Problem

Given an integer array nums, consider any contiguous subarray nums[l..r].

A subarray is called balanced if the product of all its elements is equal to:

length(subarray)×max(subarray)\text{length(subarray)} \times \max(\text{subarray})

Your task is to return the maximum length of a balanced subarray.

If no balanced subarray exists, return 0.

Notes

  • The subarray must be contiguous.
  • The product can become very large, so efficient reasoning is needed.
  • The array may contain positive integers; the intended formulation is based on exact integer equality.

Intuition

This problem asks you to compare a multiplicative quantity over a window against a value derived from its size and maximum element. A straightforward brute-force scan over all subarrays is usually too slow, so the key is to use mathematical structure and careful window reasoning.

Input Format

  • An integer array nums.
  • nums[i] represents the value at index i.

Output Format

  • Return a single integer: the maximum length of a contiguous subarray satisfying the equality condition.

Constraints

  • 1 <= nums.length
  • Elements are integers.
  • The exact hidden constraints are not provided in the source metadata; solve with an approach suitable for interview settings and typical LeetCode-sized inputs.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 1, 1]

Output

2

Explanation

The subarray [1, 1] has product 1 and length 2 with maximum 1, so the equality is not satisfied. But the subarray [1, 2] has product 2, length 2, and maximum 2, so it is balanced. The maximum balanced length is 2.

Example 2

Input

nums = [2, 2, 2]

Output

3

Explanation

For the whole array, product = 2 × 2 × 2 = 8 and length × max = 3 × 2 = 6, so it is not balanced. The balanced subarrays are the single-element subarrays [2], each with product 2 and length × max = 1 × 2 = 2. The answer is 1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.