题目:最大字段积。
分析:dp,最大字段和类似物。求解过程同最大字段和。
这里注意,设置两个状态:以本元素结束时,最大正值和最小的负值。
更新时。假设data[i]为正,则相应跟新,假设data[i]为负。则交叉跟新,
data[i]为0时,当前最大值,最小值置零。
本题数据较小,能够直接用O(n^2)暴力算法。枚举起始结束位置就可以。
说明:用long long防止溢出。
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int data[20];
int main()
{
int n,t = 1;
while (cin >> n) {
for (int i = 1 ; i <= n ; ++ i)
cin >> data[i];
long long max = 0,neg = 0,pos = 0,tem;
for (int i = 1 ; i <= n ; ++ i) {
if (data[i] == 0)
neg = pos = 0;
else if (data[i] > 0) {
pos = pos*data[i];
neg = neg*data[i];
if (!pos) pos = data[i];
}else if (data[i] < 0) {
tem = pos*data[i];
pos = neg*data[i];
neg = tem;
if (!neg) neg = data[i];
}
if (max < pos && data[i])
max = pos;
}
cout << "Case #" << t ++ << ": The maximum product is " << max << ".\n\n";
}
return 0;
}