Bob needs money, and since he knows you are here, he decided to gamble intelligently. The game is rather simple: each player gets a sequence of integers. The players must determine, by using their mega-pocket computers, which is the maximum product value which can be computed with non empty sub-sequences of consecutive numbers from the given sequence. The winner is the one which gets first the right result.
Can you help Bob with a program to compute quickly the wanted product, particularly when the sequence is quite long?
Input
The input file contains sequences of numbers. Each number will have at most 5 digits. There will be at most 100 numbers in each sequence. Each sequence starts on a new line and may continue on several subsequent lines. Each sequence ends with the number -999999 (which is not part of the sequence).
Output
The maximum sub-sequence product for each sequence must be written on the standard output, on a different line. A simple example is illustrated in the sample below.
Sample Input
1 2 3 -999999
-5 -2 2 -30 -999999
-8 -999999
-1 0 -2 -999999
Sample Output
6 120 -8 0
最大子序列乘积和分别记录最小和最大的乘积。类似与最大子序列和的dp思想,由于是乘积用到了java BigInterger类否则会超出数据范围。代码如下。
package com.company;
import java.math.BigInteger;
import java.util.Scanner;
/**
* Created by wangruoxuan on 16/2/6.
*/
public class MainDp {
public static BigInteger maxTwo(BigInteger a,BigInteger b){
if(a.compareTo(b)>0){
return a;
}else {
return b;
}
}
public static BigInteger maxThree(BigInteger a, BigInteger b, BigInteger c){
return maxTwo(a,maxTwo(b,c));
}
public static BigInteger minThree(BigInteger a,BigInteger b,BigInteger c){
if(a.compareTo(b)>0){
if(b.compareTo(c)>0){
return c;
}else {
return b;
}
}else {
if(a.compareTo(c)>0){
return c;
}else {
return a;
}
}
}
public static void main(String[] args){
final int max_n = 10000;
int[] a = new int[max_n];
int x;
Scanner input = new Scanner(System.in);
BigInteger[] dp_max = new BigInteger[max_n];
BigInteger[] dp_min = new BigInteger[max_n];
while (input.hasNext()){
int pos = 0;
while (input.hasNext()&&(x=input.nextInt())!=-999999){
a[pos++] = x;
}
dp_max[0] = BigInteger.valueOf(a[0]);
dp_min[0] = BigInteger.valueOf(a[0]);
for (int i = 1;i<pos;i++){
BigInteger bigElement = BigInteger.valueOf(a[i]);
dp_max[i] = maxThree(dp_max[i-1].multiply(bigElement),bigElement,dp_min[i-1].multiply(bigElement));
dp_min[i] = minThree(dp_max[i-1].multiply(bigElement),bigElement,dp_min[i-1].multiply(bigElement));
}
BigInteger ans = dp_max[0];
for(int i = 1;i<pos;i++){
ans = maxTwo(ans,dp_max[i]);
}
System.out.println(ans);
}
}
}