1. 程式人生 > >最大乘積

最大乘積

最大乘積 連續 while put style ext div ring arr

問題描述:輸入n個元素組成的序列S,你需要找出一個乘積最大的連續子序列。

  樣例輸入

    3
    2 4 -3
    5
    2 5 -1 2 -1
    7
    -2 4 0 3 5 8 -1

解題關鍵:因為要求連續,所以當最大值小於當前值時,立刻開啟新的子串!用數組保存分別到達數組每一個值時對應的最大值和最小值!

import java.util.Scanner;
/**
 * 最大乘積
 * @author NEU-2015
 *
 */
public class Demo {
    public static void main(String[] args) {
        Scanner input 
= new Scanner(System.in); long[] max; long[] min; int count; int[] array; long result; while(input.hasNext()) { count = input.nextInt(); array = new int[count]; max = new long[count]; min = new long[count];
for(int i = 0; i < count; i++) { array[i] = input.nextInt(); } max[0] = array[0]; min[0] = array[0]; for(int i = 1; i < count; i++) { max[i] = Max(max[i-1]*array[i], min[i-1]*array[i], array[i]); min[i]
= Min(max[i-1]*array[i], min[i-1]*array[i], array[i]); } result = max[0]; for(int i = 1; i < count; i++) { if(max[i] > result) { result = max[i]; } } System.out.println(result); } input.close(); } private static long Max(long l, long m, int i) { long max = l; if(m > max) { max = m; } if(i > max) { max = i; } return max; } private static long Min(long l, long m, int i) { long min = l; if(m < min) { min = m; } if(i < min) { min = i; } return min; } }

最大乘積