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:

  1. Initialize max_product and min_product to 1.
  2. Iterate through the array:
    • For each element num in the array:
      • Update max_product and min_product as follows:
        • If num is greater than both max_product and min_product, update max_product to num and set min_product to num.
        • If num is less than both max_product and min_product, update min_product to num and set max_product to num * max_product.
        • If num is equal to either max_product or min_product, do nothing.
  3. The maximum product subset is the one that ends at the position where max_product was 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.