Uva11059

Maximum Product UVA - 11059

Given a sequence of integers S = {S1,S2,...,Sn}, you should determine what is the value of the maximum positive product involving consecutive terms of S. If you cannot find a positive sequence, you should consider 0 as the value of the maximum product.
Input Each test case starts with 1 ≤ N ≤ 18, the number of elements in a sequence. Each element Si is an integer such that −10 ≤ Si ≤ 10. Next line will have N integers, representing the value of each element in the sequence. There is a blank line after each test case. The input is terminated by end of file (EOF).
Output
For each test case you must print the message: ‘Case #M: The maximum product is P.’, where M is the number of the test case, starting from 1, and P is the value of the maximum product. After each test case you must print a blank line.
Sample Input
3 2 4 -3
5 2 5 -1 2 -1
Sample Output
Case #1: The maximum product is 8.
Case #2: The maximum product is 20.

 

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <queue>
 4 #include <vector>
 5 #include<string.h>
 6 #include<map>
 7 #include<bits/stdc++.h>
 8 #define LL long long
 9 using namespace std;
10 LL ay[20];
11 int main()
12 {
13     int n,no=0;
14     LL ans,sum;
15     while(~scanf("%d",&n))
16     {
17         no++;
18         ans=-1;
19         for(int i=0;i<n;i++)
20             scanf("%lld",&ay[i]);
21         for(int i=0;i<n;i++)
22             for(int j=i;j<n;j++){
23             sum=1;
24             for(int k=i;k<=j;k++)
25             {
26                 sum*=ay[k];
27                 ans=max(ans,sum);
28             }
29             }
30         if(ans<0)ans=0;
31         printf("Case #%d: The maximum product is %lld.\n\n",no,ans);
32     }
33     return 0;
34 }

题意:

求最大的连续子列的乘积。如果乘积为负数,则输出0。

注意点:

枚举起点终点求解。ans为最大值,sum为动态过程值。

1.ans的初值应该设为负数,不然如果设为正数的话,当乘积为负数的话,ans=max(ans,sum)>0,无法得到0。

上一篇:LeetCode 962. Maximum Width Ramp


下一篇:LeetCode 53. 最大子序和(Maximum Subarray)