Notes for competitive programming

Editorial

Codeforces

1042c-prod

Array Product

Let’s deal with a simpler problem than what is asked for.

Given a list LL, determine the subset LL' of LL that will give the maximum product.

Obviously, LL' must contain all positive elements of LL. Since the product of two negative numbers is positive, then LL' must contain an even number of negative numbers. If there are an odd number of negative numbers, we exclude the one least in magnitude, i.e. the largest negative number.

Thus, to get the maximum product of LL, we have to delete everything in LL that is zero; if LL has an odd number of negative numbers, we must delete that too.

Since we only have a single delete operation available to us, we have to merge everything in LLL \setminus L', then delete the merged element. We can then proceed to merge everything in LL.

Depending on the method you choose to implement this, pay attention to some edge cases:

  1. all positive values or all negative values, with nn being even - in both cases, nothing should be deleted;
  2. all negative values with nn being odd;
  3. all zero values;
  4. a mix of negatives and positives but with no zero-value.
Editorial created
2025-01-29T00:00:00.000Z
Last updated
2025-01-29T00:00:00.000Z
Solution summary

Merge all undesirable elements, delete the merge, then merge the rest.

Running time

O(n)O(n)

Problem link

On Codeforces

Tags

constructive-algorithm