709949. Maximum product subset of an array
Medium
Maximum Product Subset of an Array
Summary
Given a non-empty array nums containing only positive integers, find the maximum product subset. The maximum product subset is defined as the product of all elements in the subset that has the largest value.
Detailed Explanation
To solve this problem, we can iterate through the array and keep track of the maximum and minimum products ending at each position. We start with a maximum product max_product and a minimum product min_product, both initialized to 1 (the smallest possible product).
Here's the step-by-step breakdown:
- Initialize
max_productandmin_productto 1. - Iterate through the array:
- For each element
numin the array:- Update
max_productandmin_productas follows:- If
numis greater than bothmax_productandmin_product, updatemax_producttonumand setmin_producttonum. - If
numis less than bothmax_productandmin_product, updatemin_producttonumand setmax_producttonum * max_product. - If
numis equal to eithermax_productormin_product, do nothing.
- If
- Update
- For each element
- The maximum product subset is the one that ends at the position where
max_productwas last updated.
Time complexity: O(n), where n is the length of the array.
Space complexity: O(1), as we only use a constant amount of space to store max_product and min_product.
Optimized Solutions
Java
public int maxProduct(int[] nums) {
int max_product = 1;
int min_product = 1;
for (int num : nums) {
if (num > max_product && num > min_product) {
max_product = num;
min_product = num;
} else if (num < max_product && num < min_product) {
max_product = num * max_product;
min_product = num;
}
}
return max_product;
}