Wednesday, November 11, 2015

UVa 11059 - Maximum Product

// UVa 11059 - Maximum Product

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int t = 0;
		while (scanner.hasNextInt()) {
			int n = scanner.nextInt();
			t++;
			boolean still_head = true;
			BigInteger head = BigInteger.ONE;
			BigInteger tail = BigInteger.ONE;
			BigInteger p = BigInteger.ONE;
			int m = 0;
			BigInteger s = BigInteger.ZERO;
			int count = 0;
			for (int i = 0; i < n; i++) {
				BigInteger a = scanner.nextBigInteger();
				if (a.compareTo(BigInteger.ZERO) != 0) {
					m++;
					p = p.multiply(a);
					tail = tail.multiply(a);
					if (still_head)
						head = head.multiply(a);
					if (a.compareTo(BigInteger.ZERO) < 0) {
						tail = a;
						still_head = false;
						count++;
					}
				} else {
					BigInteger sol;
					if (p.compareTo(BigInteger.ZERO) > 0)
						sol = p;
					else {
						if (head.compareTo(tail) < 0)
							sol = p.divide(tail);
						else
							sol = p.divide(head);
					}
					if ((p.compareTo(BigInteger.ZERO) < 0 && m <= 1) || (m == 0))
						sol = BigInteger.ZERO;
					if (sol.compareTo(s) > 0)
						s = sol;
					still_head = true;
					head = BigInteger.ONE;
					tail = BigInteger.ONE;
					p = BigInteger.ONE;
					m = 0;
				}
			}
			BigInteger sol;
			if (p.compareTo(BigInteger.ZERO) > 0)
				sol = p;
			else {
				if (head.compareTo(tail) < 0)
					sol = p.divide(tail);
				else
					sol = p.divide(head);
			}
			if ((p.compareTo(BigInteger.ZERO) < 0 && m <= 1) || (m == 0))
				sol = BigInteger.ZERO;
			if (sol.compareTo(s) > 0)
				s = sol;
			System.out.println("Case #" + t + ": The maximum product is " + s + ".");
			System.out.println();
		}
	}

}

No comments:

Post a Comment