您的位置:首页 > 其它

UVa - 11059 - Maximum Product(枚举)

2016-10-10 22:45 309 查看


题目意思:输入n,然后输入n个数字,求子阵列的最大乘积是多少,如果最大乘积是负数,那么输出0。每组输出后面有一个空行,最后一组也有空行。

思路:枚举出所有的子阵列,求出其中最大乘积是多少(包括一个元素),因为是求连续子阵列,所以只需要枚举出子阵列的起点和终点,然后相乘起来求乘积。题目中给出的n最大是18,给出的元素最大是10,所以最大的乘积超不过10^18,用long long声明变量防止溢出。

#include<iostream>
#include<cstdio>
using namespace std;
int n;
int count=1;
int main(){
// freopen("input.txt","r",stdin);
while(cin>>n){
int a
;
for(int i=0 ;i<n ;i++) cin>>a[i];

long long max = -1;

for(int i=0 ;i<n ;i++){
long long ans = a[i];
for(int j=i+1; j<n ;j++){
ans *= a[j];
if(max<ans)
max = ans;
}
//
if(a[i]>max)
max = a[i];
}
if(max<0){
printf("Case #%d: The maximum product is 0.\n\n",count++);
}else{
printf("Case #%d: The maximum product is %lld.\n\n",count++,max);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: