Saturday, March 10, 2018

 Get Max product from an integer array
public int maxProduct(List<int> input)
{
int lo = 1;
int hi = 1;
int result = 1;
for (int i = 0; i < input.Count; i++)
{
if (input[i]  == 0)
{
lo = 1;
hi = 1;
}
else{
   int temp = hi * input[i];
   if (input[i] > 0)
   {
       hi = temp;
       lo = Math.Min(lo * input[i], 1);
   }
   else
   {
      lo = temp;
      hi = Math.Max(lo * input[i], 1);
   }
}
if (result < hi)
    result = hi;
}
return result;
}
This is for contiguous subsequence.
We could also write the above if else in dynamic programming with recursion to include either the current element or exclude it. If an element is not included we multiply 1. If it is included we multiply the element to the maximum  of the recursion found as for example in positive integer array
int getMaxProduct(List<int> A, int index)
{
assert (A.all (x=> x>=0));
if (index  == A.Length)
     return 1;
int remaining = GetMaxProduct (A, index +1);
return Math.max (A [index] * remaining,  1 * remaining) ;
}
which is the same as saying replace all 0 with 1 in the sorted positive integer array
Therefore we can even sort the integer array replace all 0 with 1 and trim the odd count negative number to the left of zero
double GetMaxProduct (List <int> A)
{
A.sort ();
A.replaceAll(0, 1);
int count = A.Count (x => x < 0);
if (count > 0 && count % 2 == 1)
{
    A.replace (A.min (x => x < 0), 1);
}
return A.Product ();
}

No comments:

Post a Comment