importmathdefget_product_of_3(array_of_ints):iflen(array_of_ints)<3:return0min_max=-math.infmin_max_i=0maxes=[min_max,min_max,min_max]max_neg=0max_neg_i=0negs=[0,0]forintinarray_of_ints:ifint>min_max:maxes[min_max_i]=intmin_max_i,min_max=min(enumerate(maxes),key=lambdax:x[1])ifint<max_neg:negs[max_neg_i]=intmax_neg_i,max_neg=max(enumerate(negs),key=lambdax:x[1])prod_maxes=maxes[0]*maxes[1]*maxes[2]prod_negs=negs[0]*negs[1]# This condition is only needed for `[n,p,p]`, to not return the invalid product of `0` when the product of maxes is negative.
ifprod_negs!=0:returnmax(prod_negs*max(maxes),prod_maxes)returnprod_maxes
If we instead explicitly return the product of 3 inputs, this condition is no longer needed:
Another possible optimization, for input such as [...-100,-99,-98,-97,1,-96,-95,-94...] is to stop expecting the "all negatives" case. This can easily be done by resetting all negative maxes to 0, so that incoming negatives are always smaller:
Okay, I think I got it:
If we instead explicitly return the product of 3 inputs, this condition is no longer needed:
Another possible optimization, for input such as
[...-100,-99,-98,-97,1,-96,-95,-94...]is to stop expecting the "all negatives" case. This can easily be done by resetting all negative maxes to 0, so that incoming negatives are always smaller: