Maximum Product Subarray [leetcode]

本文介绍了一种寻找具有最大乘积的连续子数组的方法。通过动态规划思想,文章提出了一种时间复杂度为O(n)的高效算法,并给出了具体实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
	Find the contiguous subarray within an array (containing at least one number) which has the largest product.
	For example, given the array [2,3,-2,4],
	the contiguous subarray [2,3] has the largest product = 6.
*/
#include <iostream>
using namespace std;
/*
	超时O(n2)
	
class Solution{
public:
	int maxProduct(int A[],int n)
	{
		int * temp = new int[n];
		int maxproduct = A[0];
		for(int i = 0;i < n;i ++)
			temp[i] = 1;
			
		for(int j = 0;j < n;j ++)// j 连续的项数-1
		{	for(int i = 0;i < n - j;i ++)
			{
				temp[i] *= A[i + j];
				if(temp[i] > maxproduct)
					{
						maxproduct = temp[i];
					}
				cout << i + j << endl;
			}
		}
		delete [] temp;
		return maxproduct;
	}
};
*/
//动态规划 思路 
//	s[i] :表示以第i个结尾的乘积 
//  s`[i] 表示以第i个结尾的最小连续乘积
// s[i] = max(A[i],s[i-1]*A[i],s`[i-1]*A[i])
// s`[i] = max(A[i],s[i-1]*A[i],s`[i-1]*A[i])
class Solution{
public:
	int maxProduct(int A[],int n)
	{
		int maxhere = A[0];
		int minhere = A[0];
		int maxpre = A[0];
		int minpre = A[0];
		int maxproduct = A[0];
		for(int i =  1;i < n;i ++)
		{
			maxhere = max(maxpre*A[i],minpre*A[i],A[i]);
			minhere = min(maxpre*A[i],minpre*A[i],A[i]);
			maxproduct = max(maxproduct,maxhere,A[0]);
			maxpre = maxhere;
			minpre =  minhere;
		}
		return maxproduct;
	}
	int max(int s1,int s2,int s3)
	{
		if(s1 < s2)
			{
			if(s2 < s3)
				return s3;
			else 
				return s2;
			}
		else
			{
			if(s1 > s3)
				return s1;
			else
				return s3;
			}
	}
	int min(int s1,int s2,int s3)
	{
		if(s1 < s2)
		{
			if(s1 < s3)
				return s1;
			else
				return s3;
			
		}
		else
		{
			if(s2 < s3)
				return s2;
			else
				return s3;
		}
	}
};


使用O(1)空间复杂度和O(n)空间复杂度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值