简体   繁体   中英

Maximum product subarray in java

This Question is Maximum Product Subarray I have wrote the Solution but it is not getting exact answer.

package practicePrograms;

import java.util.*;

public class max_product_subarray {
    public static void main(String[] args) {
        int[] arr = {8, -2, -2, 0, 8, 0, -6, -8, -6, -1};
        System.out.println(new Solun().maxProduct(arr, arr.length));
    }
}

class Solun {
    long maxProduct(int[] arr, int n) {
        long max = 1;
        long temp;
        List<Integer> at = new ArrayList<>();
        for (int i = 0; i < n; ) {
            temp = max;
            max = temp * arr[i];
            if (max == 0) {
                if (temp < 0) {
                    temp = temp * -1;
                }
                at.add((int) temp);
                max = 1;
            }
            i++;
        }
        Collections.sort(at);
        long maxi = at.get(at.size() - 1);
        return maxi;
    }
}

Here the ArrayList should contain [32, 8, 288] in sorted way but it only contain [8, 32] why not 288 ?

@csalmhof has pointed out the error with your solution. But the following is a working solution that may help you.

long maxProduct(int[] arr, int n) {
    if (n == 1)
        return arr[0];
    long ans = 0;
    long maxPosCurr = 0;
    long maxNegCurr = 0;
    for (int elem : arr) {
        if (elem >= 0) {
            maxPosCurr = Math.max(maxPosCurr * elem, elem);
            maxNegCurr = Math.min(maxNegCurr * elem, elem);
        } else {
            long temp1 = Math.max(maxNegCurr * elem, elem);
            long temp2 = Math.min(maxPosCurr * elem, elem);
            maxPosCurr = temp1;
            maxNegCurr = temp2;
        }
        ans = Math.max(ans, maxPosCurr);
    }
    return ans;
}

Let me know if you have any doubts with the working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM