java – 最大产品子阵列问题

这是问题和代码(我搜索解决方案,大多数是相似的,发布一个易于阅读),我的问题是针对以下两行,

 imax = max(A[i], imax * A[i]);
 imin = min(A[i], imin * A[i]);

为什么我们需要单独考虑A [i],为什么不写作为,

 imax = max(imin * A[i], imax * A[i]);
 imin = min(imin * A[i], imax * A[i]);

在具有最大乘积的数组(包含至少一个数字)中查找连续的子数组.

例如,给定数组[2,3,-2,4],
连续的子阵列[2,3]具有最大的乘积= 6.

int maxProduct(int A[], int n) {
    // store the result that is the max we have found so far
    int r = A[0];

    // imax/imin stores the max/min product of
    // subarray that ends with the current number A[i]
    for (int i = 1, imax = r, imin = r; i < n; i++) {
        // multiplied by a negative makes big number smaller, small number bigger
        // so we redefine the extremums by swapping them
        if (A[i] < 0)
            swap(imax, imin);

        // max/min product for the current number is either the current number itself
        // or the max/min by the previous number times the current one
        imax = max(A[i], imax * A[i]);
        imin = min(A[i], imin * A[i]);

        // the newly computed max value is a candidate for our global result
        r = max(r, imax);
    }
    return r;
}

提前致谢,

最佳答案

imax = max(A[i], imax * A[i]);

当你单独考虑A [i]时,你基本上考虑了从A [i]开始的序列.

当你最初用A [0]初始化imin和imax时,你正在做类似的事情.

对于imin案例也是如此.

小例子:

数组= {-4,3,8,5}

初始化:imin = -4,imax = -4

迭代1:i = 1,A [i] = 3

imax = max(A [i],imax * A [i]); – > imax = max(3,-4 * 3); – > imax = 3

因此,当imax为负且A [i]为正时,A [i]可以是最大的.

点赞