Find the longest contiguous subarray whose element product equals the product of its length and its maximum element.
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:
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 indexi.
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.
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.