package algorithm.misc;
import util.*;
public class MaxProductOfN1 {
private static int exceptIndex = -1;
public static long regMethod(int data[])
{
long ret = Long.MIN_VALUE;
long tmp = 1;
for(int i = 0; i < data.length; i++)
{
tmp = 1;
for(int j = 0; j < data.length; j++)
{
if(j != i)
{
tmp *= data[j];
}
}
if(tmp > ret)
{
ret = tmp;
exceptIndex = i;
}
}
return ret;
}
public static long dp(int data[])
{
long ascent[] = new long[data.length + 1];
ascent[0] = 1;
for(int i = 0; i < data.length; i++)
{
ascent[i + 1] = ascent[i] * data[i];
}
long descent[] = new long[data.length + 1];
descent[0] = 1;
for(int i = 0; i < data.length; i++)
{
descent[i + 1] = descent[i] * data[data.length - i - 1];
}
long ret = Long.MIN_VALUE;
long tmp = 1;
for(int i = 0; i < data.length; i++)
{
tmp = ascent[i] * descent[data.length - i - 1];
if(tmp > ret)
{
ret = tmp;
exceptIndex = i;
}
}
return ret;
}
public static long analyse(int data[])
{
long ret = 1;
int numOfPos = 0, numOfNeg = 0, numOfZero = 0;
for(int i = 0; i < data.length; i++)
{
if(data[i] == 0)
{
numOfZero++;
}
else if(data[i] > 0)
{
numOfPos++;
}
else
{
numOfNeg++;
}
}
int index = -1;
//There are zeros
if(numOfZero > 0)
{
//More than 2 zeros
if(numOfZero > 1)
{
exceptIndex = 0;
return 0;
}
//Only 1 zero
else
{
//The number of negative number is even.
if(numOfNeg % 2 == 0)
{
index = getIndex(data, 0);
exceptIndex = index;
return multipleExcept(data, index);
}
//odd
else
{
exceptIndex = 0;
return 0;
}
}
}
else if(numOfNeg % 2 == 1)
{
index = -1;
int maxNegValue = Integer.MIN_VALUE;
for(int i = 0; i < data.length; i++)
{
if(data[i] < 0 && data[i] > maxNegValue)
{
maxNegValue = data[i];
index = i;
}
}
exceptIndex = index;
return multipleExcept(data, index);
}
else
{
index = -1;
int minPosValue = Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++)
{
if(data[i] > 0 && data[i] < minPosValue)
{
minPosValue = data[i];
index = i;
}
}
exceptIndex = index;
return multipleExcept(data, index);
}
}
public static int getIndex(int data[], int value)
{
for(int i = 0; i < data.length; i++)
{
if(data[i] == value)
{
return i;
}
}
return -1;
}
public static long multipleExcept(int data[], int index)
{
long ret = 1;
for(int i = 0; i < data.length; i++)
{
if(i != index)
{
ret *= data[i];
}
}
return ret;
}
private static void formatOutputRet(long ret, int data[])
{
System.out.print("Result: " + ret);
System.out.print(", Except Index = " + exceptIndex + ", " + data[exceptIndex]);
System.out.println();
}
public static void test1()
{
// int data[] = {20, 2, 0, -7, -7, 6, 7, 0, 9, 10};
int data[] = ArrayUtil.generate(10, 101);
ArrayUtil.output(data);
long ret = regMethod(data);
formatOutputRet(ret, data);
long ret1 = dp(data);
formatOutputRet(ret1, data);
long ret2 = analyse(data);
formatOutputRet(ret2, data);
}
/**
* @param args
*/
public static void main(String[] args) {
test1();
}
}