天天看點

數組連續子序列的最大和&最大積

int MaxProduct(int* arr, int len)
{
    int dp1 = arr[0];
    int dp2 = arr[0];
	int largest = arr[0];
    for (int i = 1; i < len; ++i)
    {
        int tmp1 = dp1*arr[i];
        int tmp2 = dp2*arr[i];
        dp1 = max(tmp1,tmp2,arr[i]);
        dp2 = min(tmp1,tmp2,arr[i]);
		if(dp1 > largest) largest = dp1;
    }
	return largest;
}

int MaxSum(int* arr, int len)
{
	int largest = arr[0];
	int cur = arr[0];
	for(int i = 1; i < len; i++)
	{
		if(cur<0) cur = arr[i];
		else
			cur += arr[i];
		if(cur > largest) largest = cur;
	}
	return largest;
}
           

Max[i] = max(Max[i-1]+arr[i], arr[i]) = arr[i] + max(0, Max[i-1]);

繼續閱讀