首页 > 代码库 > leetcode Maximum Product Subarray
leetcode Maximum Product Subarray
#include <iostream>
#include <cstdlib>
using namespace std;
int min(int a, int b){
return a>b?b:a;
}
int max(int a, int b){
return a>b?a:b;
}
int maxProduct(int A[], int n) {
if (n == 0 ){
return 0;
}
if (n == 1 )
{
return A[0];
}
int maxproduct = A[0];
int minproduct = A[0];
int result = maxproduct;
int i = 0;
for(i = 1; i < n; i++){
int tmp = maxproduct;
maxproduct = max(max(maxproduct*A[i], A[i]), minproduct*A[i] );
minproduct = min(min(tmp*A[i], A[i]), minproduct*A[i] );
result = max(maxproduct,result);
}
return result;
}
int main(int argc, char** argv) {
int A[] = {2,3,-2,4};
int n = 4;
cout<<maxProduct(A,n)<<endl;
return 0;
}
#include <cstdlib>
using namespace std;
int min(int a, int b){
return a>b?b:a;
}
int max(int a, int b){
return a>b?a:b;
}
int maxProduct(int A[], int n) {
if (n == 0 ){
return 0;
}
if (n == 1 )
{
return A[0];
}
int maxproduct = A[0];
int minproduct = A[0];
int result = maxproduct;
int i = 0;
for(i = 1; i < n; i++){
int tmp = maxproduct;
maxproduct = max(max(maxproduct*A[i], A[i]), minproduct*A[i] );
minproduct = min(min(tmp*A[i], A[i]), minproduct*A[i] );
result = max(maxproduct,result);
}
return result;
}
int main(int argc, char** argv) {
int A[] = {2,3,-2,4};
int n = 4;
cout<<maxProduct(A,n)<<endl;
return 0;
}
leetcode Maximum Product Subarray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。