Leetcode 152. Maximum Product Subarray
Given an integer array nums
, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
public class Solution {
public int maxProduct(int[] nums) {
// Edge case: Empty array is not allowed as per problem statement
if(nums.length == 0) return 0;
// Initialize the variables for tracking maximum and minimum products
int maxProduct = nums[0];
int minProduct = nums[0];
int result = nums[0];
// Iterate through the array starting from index 1
for(int i = 1; i < nums.length; i++) {
// If the current number is negative, swap the max and min products
if(nums[i] < 0){
int temp = maxProduct;
maxProduct = minProduct;
minProduct = temp;
}
// Update the maximum and minimum products ending at the current position
maxProduct = Math.max(nums[i], maxProduct * nums[i]);
minProduct = Math.min(nums[i], minProduct * nums[i]);
// Update the result with the maximum found so far
result = Math.max(result, maxProduct);
}
return result;
}
}
O(n)
where n
is the number of elements in the input array. We go through the array once.O(1)
. We use a constant amount of extra space. The variables maxProduct
, minProduct
, and result
are used to keep track of the required values.This approach ensures that we efficiently find the maximum product of a contiguous subarray while keeping the implementation straightforward.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?