#1567
Maximum Length of Subarray With Positive Product
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves checking every possible subarray and calculating the product of its elements. If the product is positive, we keep track of the maximum length found.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through each element in the array as a starting point for subarrays.
- 2Step 2: For each starting point, iterate through all possible ending points to form subarrays.
- 3Step 3: Calculate the product of the current subarray and check if it's positive. If it is, update the maximum length.
solution.py10 lines
1def maxLength(nums):
2 max_length = 0
3 n = len(nums)
4 for i in range(n):
5 product = 1
6 for j in range(i, n):
7 product *= nums[j]
8 if product > 0:
9 max_length = max(max_length, j - i + 1)
10 return max_lengthℹ
Complexity note: This complexity arises because we are using nested loops to check all subarrays, leading to a quadratic number of operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.