您的位置:首页 > 其它

最大乘积

2014-03-14 14:35 225 查看
/*
输入那个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个
最大乘积不是正数,应输出-1(表示无解)。1<=n<=18 , -10<=Si<=10 *
样例输入:
3
2 4 -3
5
2 5 -1 2 -1
样例输出:
8
20
*
*/
import java.util.*;

public class Main6 {
public static int n;
public static int[] array;

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
n = sc.nextInt();
array = new int
;
long[] tmp = new long
;
// 初始化保存各个起点和终点的乘积
for (int i = 0; i < n; i++) {
tmp[i] = 1;
}
// 读数和计算乘积
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
if (i > 0)
tmp[i] *= tmp[i - 1] * array[i];
else
tmp[i] = array[i];
}
long max = tmp[0];
// 遍历数组,找出乘积最大的数
for (int i = 1; i < n; i++) {
max = max > tmp[i] ? max : tmp[i];
}
System.out.println(max);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: