最大乘积

来源:互联网 发布:法兰克宏程序编程入门 编辑:程序博客网 时间:2024/05/18 02:07
/* 输入那个元素组成的序列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 stubScanner sc = new Scanner(System.in);while (sc.hasNext()) {n = sc.nextInt();array = new int[n];long[] tmp = new long[n];// 初始化保存各个起点和终点的乘积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];elsetmp[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);}}}

0 0