Maximum product subset of an array

Pattern: Candy and assign cookies

medium

Multiply all non-zero values. If the count of negatives is odd, divide out the negative closest to zero. Special cases: all zeros gives 0, and a single negative with only zeros besides gives 0 (pick a zero instead). A one-element array is that element.

The problem

Return the largest product of a non-empty subset of the array (any elements, not necessarily neighbours). [-1, -1, -2, 4, 3] gives 24; [-1, 0] gives 0. The values are small enough that the answer fits in 64 bits.

Think first

  • Do zeros ever help?
  • When is the product of all non-zero values negative?
  • Which negative should you leave out then?

Hints

    Brute force, and why it fails

    Try every subset: O(2ⁿ × n).

    The key insight

    Every positive and every pair of negatives increases the size of the product, so take everything except, at most, the weakest negative.

    Dry run

    product-24
    negatives3

    arr = [-1, -1, -2, 4, 3]. Product of the non-zero values: -24, with 3 negatives.

    Step 1 of 3

    The plan

    if n == 1: return arr[0]
    multiply non-zero values; count negatives and zeros; track the largest negative
    if all zeros: return 0
    if odd negatives: if one negative and the rest zeros: return 0; else divide by the largest negative
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass.

    Edge cases

    • One negative alone: that negative.
    • One negative and zeros: 0.
    • All zeros: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public long maxProduct(int[] arr) {
            if (arr.length == 1) return arr[0];
            long product = 1;
            int negatives = 0, zeros = 0, largestNegative = Integer.MIN_VALUE;
            for (int x : arr) {
                if (x == 0) { zeros++; continue; }  // a zero never helps a nonzero product
                if (x < 0) { negatives++; largestNegative = Math.max(largestNegative, x); }
                product *= x;
            }
            if (zeros == arr.length) return 0;
            if (negatives % 2 == 1) {
                if (negatives == 1 && zeros + negatives == arr.length) return 0;   // one negative and zeros: pick a zero
                product /= largestNegative;         // drop the negative closest to zero
            }
            return product;
        }
    }

    C++

    class Solution {
    public:
        long long maxProduct(vector<int>& arr) {
            if (arr.size() == 1) return arr[0];
            long long product = 1;
            int negatives = 0, zeros = 0, largestNegative = INT_MIN;
            for (int x : arr) {
                if (x == 0) { zeros++; continue; }  // a zero never helps a nonzero product
                if (x < 0) { negatives++; largestNegative = max(largestNegative, x); }
                product *= x;
            }
            int n = static_cast<int>(arr.size());
            if (zeros == n) return 0;
            if (negatives % 2 == 1) {
                if (negatives == 1 && zeros + negatives == n) return 0;   // one negative and zeros: pick a zero
                product /= largestNegative;         // drop the negative closest to zero
            }
            return product;
        }
    };

    Python

    class Solution:
        def maxProduct(self, arr: list[int]) -> int:
            if len(arr) == 1:
                return arr[0]
            nonzero = [x for x in arr if x != 0]    # a zero never helps a nonzero product
            negatives = [x for x in nonzero if x < 0]
            if not nonzero:
                return 0
            if len(negatives) % 2 == 1:
                if len(negatives) == 1 and len(nonzero) == 1:
                    return 0                        # one negative and zeros: pick a zero
                nonzero.remove(max(negatives))      # drop the negative closest to zero
            product = 1
            for x in nonzero:
                product *= x
            return product

    Common mistakes

    • Dropping the most negative value instead of the one nearest zero.
    • Returning a negative product when a zero is available.

    Similar problems