
Problem
Solution
Submissions
Maximum Product Subarray
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C# program to implement the MaxProduct(int[] nums)
function, which finds the contiguous subarray within an array of integers that has the largest product. The function should return the product of that subarray.
Example 1
- Input: nums = [2, 3, -2, 4]
- Output: 6
- Explanation:
- Step 1: Consider all possible subarrays of the input array.
- Step 2: Calculate the product of each subarray.
- Step 3: The subarray [2, 3] has the largest product = 6.
- Step 4: Return the maximum product, which is 6.
Example 2
- Input: nums = [-2, 0, -1]
- Output: 0
- Explanation:
- Step 1: Consider all possible subarrays of the input array.
- Step 2: Calculate the product of each subarray.
- Step 3: The subarray [0] has the largest product = 0.
- Step 4: Return the maximum product, which is 0.
Constraints
- 1 ≤ nums.length ≤ 2 * 10^4
- -10 ≤ nums[i] ≤ 10
- The array may contain both positive and negative integers
- Time Complexity: O(n) where n is the length of the input array
- Space Complexity: O(1) for constant extra space
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Keep track of both maximum and minimum products ending at each position
- The minimum product is useful when the next element is negative (negative * negative = positive)
- When encountering zero, reset both maximum and minimum products
- Update the overall maximum product after processing each element
- Handle edge cases like single-element arrays