的最大子阵列产品使用Kadanes算法获取范围大子、阵列、算法、范围

2023-09-11 23:24:02 作者:记住丶给妳幸福的人是Me

应用Kadane算法,以获得最大的产品子阵似乎棘手。虽然我能够获得最大的产品,我不能得到正确的范围最大的产品子数组。

Applying Kadane algorithm to get max product subarray seems tricky. While I am able to get the max product, I am not really getting the correct range of the max product subarray.

http://www.geeksforgeeks.org/maximum-product-subarray/解释的方式来获得最大的产品,但我不明白,我们怎么能得到子数组的范围。

http://www.geeksforgeeks.org/maximum-product-subarray/ explains the way to get the max product but I dont get how we can get the range of the subarray.

有人可以帮助我了解的范围内的问题?这是一个标准的面试问题,我想确保我的理解对产品的情况下,而不是只是说,最大总和子数组可以修改回答最多的产品子阵情况下的逻辑。

Can someone help me understand the range issue? This is a standard interview question and I want to make sure I understand the logic for the product case instead of just saying that the max sum subarray can be modified to answer max product subarray case.

谢谢!

推荐答案

它基本上有三种情况:

在当前数字+已经 在目前的数字是-ve 在目前的数字是0

您需要有两个变量:

占据着最小值至今

最高持有的最大值到现在。

max which holds the maximum value till now.

现在的情况下3 最高将被复位到1。

Now for case 3 min and max will be reset to 1.

有关案例1 最高最大* A [1] 将是最小的分钟* A [1] 1。

For case 1: max will be max * a[i] and min will be minimum of min*a[i] and 1.

有关案例2 最高将是最大的的[I] *分钟 1 ,而值将是最大* A [1]。

For case 2: max will be maximum of a[i] * min and 1, but the min value will be max * a[i].

下面是code:

private static int getMaxProduct(int[] a){
    int minCurrent = 1, maxCurrent = 1, max = Integer.MIN_VALUE;
    for (int current : a) {
        if (current > 0) {
            maxCurrent = maxCurrent * current;
            minCurrent = Math.min(minCurrent * current, 1);
        } else if (current == 0) {
            maxCurrent = 1;
            minCurrent = 1;
        } else {
            int x = maxCurrent;
            maxCurrent = Math.max(minCurrent * current, 1);
            minCurrent = x * current;
        }
        if (max < maxCurrent) {
            max = maxCurrent;
        }
    }
    //System.out.println(minCurrent);
    return max;
}