UVA11059 最大乘积 Maximum Product

题意

给一串整数 S,你需要找到其连续子序列中乘积最大的那个,输出其乘积。如果找到的答案不是正数,那么输出 0,表示无解。

另外注意:每组输入后面都有一行空格,每组输出后面也应该有一个空行。输入以 EOF 结束。

输入 #1复制

3
2 4 -3
5
2 5 -1 2 -1

输出

Case #1: The maximum product is 8.

Case #2: The maximum product is 20.

思路:暴力枚举.

  1. 另外也可以只确定子序列左边的下标,右边的进行待定,直接走一遍,边走边进行更新.
  2. 先确定子序列左边的下标,再确定右边的下标,然后分别求解,更新结果.

需要注意,由于输入的是多行,每个样例之间有一个空行,这里应该放在样例的输出后面进行处理.

参考代码1
#include<iostream>
#include<algorithm>
using namespace std;
int arr[20],case1,n;
long long temp,ans;
int main()
{
	while(cin>>n){
//		if(case1){
//			cout<<endl;
//		}
		for(int i = 0;i < n;i++){
			cin>>arr[i];
		}
		ans = 0;
		for(int i = 0;i < n;i++){//子序列左边的下标 
			temp = 1;
			for(int j = i;j<n;j++){// 子序列右边的下标待定,边后移边进行判断更新. 
				temp *= arr[j];
				ans  = max(ans,temp);  
			} 
		}
		cout<<"Case #"<<++case1<<": The maximum product is "<<ans<<"."<<endl<<endl;
	}
}
参考代码2
#include<iostream>
#include<algorithm>
using namespace std;
int arr[20],n,case1;
long long temp,ans;//防止越界. 
int main()
{
	while(cin>>n){
		for(int i = 0;i < n;i++){
			cin>>arr[i];
		}
		ans = 0; 
		for(int i = 0; i<n;i++) //子序列的左下标 
			for(int j = i; j < n;j++){//子序列的右下标  右下标不能从i+1开始,因为可能所有的数中只有一个整数,那么这个整数就是子序列.子序列可以只有一个数字 
				temp = 1;
				for(int k = i; k <= j; k++){
					temp *= arr[k];
					//ans = max(temp,ans);这个应该放在外边,对这个子序列求完之后再更新ans. 
				}
				ans = max(temp,ans);
			}
		cout<<"Case #"<<++case1<<": The maximum product is "<<ans<<"."<<endl<<endl;
	}
	return 0;
 } 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱编程的大李子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值