找出一个序列中乘积最大的连续子序列(至少包含一个数)。
样例
样例
比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。
import java.util.Arrays;
import java.util.Scanner;
/**
* 找出一个序列中乘积最大的连续子序列(至少包含一个数)。
样例
比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。
*
* @author Dell
*
*/
public class Test91 {
public static int maxProduct(int[] nums)
{
int last_max=nums[0];
int last_min=nums[0];
int result=Integer.MIN_VALUE;
int cur_max=nums[0];
int cur_min=nums[0];
for(int i=1;i<nums.length;i++)
{
cur_max=Math.max(nums[i], Math.max(last_max*nums[i], last_min*nums[i]));
cur_min=Math.min(nums[i], Math.min(last_max*nums[i], last_min*nums[i]));
result=Math.max(result, cur_max);
last_max=cur_max;
last_min=cur_min;
}
return result;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
System.out.println(maxProduct(a));
}
}