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.
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
1 <= nums.length <= 2 * 10^4
-10 <= nums[i] <= 10
nums
is guaranteed to fit in a 32-bit integer.Q: Can the array contain zeros, and how should they be handled? A: Yes, the array can contain zeros. Subarrays consisting of zeros should be considered, and we need to reset our current product calculations when encountering a zero.
Q: Are there any constraints on the product value range? A: No, but the constraints ensure that any product will fit within a 32-bit integer bound.
Q: Should we handle larger optimizations, like a divide-and-conquer approach? A: While divide-and-conquer is an interesting approach, the problem can be efficiently solved using a linear scan with dynamic programming principles.
The main idea is to keep track of the maximum and minimum product subarray ending at each position, because a new number multiplied by a minimum product can potentially become the maximum product (e.g., negative number multiplied by a negative minimum product).
max_product
to store the final max product found so far.current_max
to store the current maximum product up to the current index.current_min
to store the current minimum product up to the current index (to handle cases where a negative number can turn a small minimum product into a large maximum product).max_product
.#include <vector>
#include <algorithm>
class Solution {
public:
int maxProduct(std::vector<int>& nums) {
if(nums.empty()) return 0; // Edge case, although constraints say nums is non-empty
int max_product = nums[0];
int current_max = nums[0];
int current_min = nums[0];
for(size_t i = 1; i < nums.size(); ++i) {
int num = nums[i];
if (num < 0) {
std::swap(current_max, current_min);
}
current_max = std::max(num, current_max * num);
current_min = std::min(num, current_min * num);
max_product = std::max(max_product, current_max);
}
return max_product;
}
};
O(n)
- Where n
is the length of the input array. We traverse the array once.O(1)
- Only a fixed amount of extra space is used.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?