例題7-2 最大乘積
阿新 • • 發佈:2018-11-28
【題目描述】
輸入n個元素的序列s,找出一個連續序列的最大乘積,若最大乘積為負數,輸出0表示無解。1<=n<=18,-10<=Si<=10
例如:
input:
5
2 5 -1 2 -1
output:
20
【分析】
連續子序列有兩個要素:起點和終點,因此只需要列舉起點與終點即可。由於每個元素的絕對值不超過10且不超過18個元素,因此最大乘積不會超過10^18,可用long long 儲存。
【程式碼】
#include<iostream> #include<string> #include<cmath> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; const int maxn = 1000 + 10; int main() { int n; while (scanf("%d", &n) != EOF) { int * a; a = new int[n]; for (int i = 0;i < n;i++) scanf("%d", &a[i]); int max_sum = 0; for (int i = 0;i < n;i++) { int cnt = 1; for (int j = i;j < n;j++) { cnt *= a[j]; if (cnt > max_sum) max_sum = cnt; } } if (max_sum < 0) cout << "0" << endl; else cout << max_sum << endl; delete[]a; } system("pause"); return 0; }