1. 程式人生 > >連續子陣列的最大乘積、最小乘積

連續子陣列的最大乘積、最小乘積

public class Main {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int n = nums.length;
        int maxHerePre = nums[0];
        int minHerePre = nums[0];
        int maxSofar = nums[0];//最大乘積
        int minSofar = nums[0];//最小乘積
        int maxHere, minHere;
        for (int i = 1; i < n; i++) {//下標從1開始
            maxHere = Math.max(Math.max(maxHerePre * nums[i], minHerePre * nums[i]), nums[i]);
            minHere = Math.min(Math.min(maxHerePre * nums[i], minHerePre * nums[i]), nums[i]);
            maxSofar = Math.max(maxSofar, maxHere);//連續子陣列最大乘積
            minSofar = Math.min(minSofar,minHere);//連續子陣列最小乘積
            maxHerePre = maxHere;
            minHerePre = minHere;
        }
        System.out.println(maxSofar+","+minSofar);
        return maxSofar;
    }//maxProduct

    public static void main(String[] args) {
//        System.out.println(new Main().maxProduct(new int[]{2,-3,-2,4}));//48
//        System.out.println(new Main().maxProduct(new int[]{2,-3,-2,4,-2,4}));//64
//        System.out.println(new Main().maxProduct(new int[]{2,3,-2,4}));//6
        System.out.println(new Main().maxProduct(new int[]{2, -3, -2, 4, -2}));//48
    }
}
//48,-96
//48