LeetCode Series: Maximum/Minimum of sum/product of Subarray/Subsequence

SubArray Related Problem:
LeetCode 152: Maximum Product subarray:
using dp, the dp[i] indicates that the maximum product of subarray ends in A[i]. however, due to we have negative number in A, and we know that any number mupltiplied by a negative will make (smaller number biggger, and bigger number smaller), so if A[i] is negative, in order to know the maximum product ends in A[i], we need to maintain the smallest of dp[i-1], and the biggest of dp[i-1]. and also, due to dp[i] only depends on dp[i-1], so each time we only maintain two variables instead of using dp array: imax and imin, and each time we preceed over with A[i], we need to update then.

int maxProduct(int A[], int n) {
    // r maintains the global maximum of dp[]
    int r = A[0];

    // imax/imin stores the max/min product of
    // subarray that ends with the current number A[i]
    int imax = r;
    int imin = r;
    for (int i = 1; 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); //due to imin * A[i] > imax * A[i], when A[i] < 0, and min * A[i] < imax * A[i], when A[i] > 0, so we swap them when A[i] < 0

        // 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]); //no matter what, we needs to update those two
        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;
}
//the code can't accepted in leetcode, donno why

LC907 Sum of subarray minimums: DONE
795 Number of subarrays with bounded Maximum DONE
363 max sum of rectangle no larger than k (This problem is different than others)
53 Maximum sum of subarray DONE
918 Maximum Sum circluar subarray DONE

523 Check if contains a subarray that sum up equals to times of k DONE

325 Maximum size subarray sum equals K DONE
209 Minimum size subarray sum DONE
560 subarray size equals K DONE
862 minimum size subarray sum at least K DONE

718 Maximum Length of repeated subarray DONE (this problem is not exactly similair to other problem here, and not the same as those sliding window solving problems)

Subsequence Related Problem:
all those subsequence sppears in String related problems instead of Array, thought array and string have no difference in general. and many subsequence replated problems are also dp problems, so take care.

posted @ 2020-05-17 09:13  EvanMeetTheWorld  阅读(27)  评论(0)    收藏  举报