题目描述如下:
暴力枚举:O(n^3)
int n,a[11111],maxnum;
int main(){
cin>>n;
for (int i=1;i<=n;i++) cin>>a[i];
for (int i=1;i<=n;i++)
for (int j=i;j<=n;j++) {
int ans=0;
for (int k=1;k<=n;k++)
if (k>=i&&k<=j) ans=ans+(1-a[k]);
else ans=ans+a[k];
maxnum=max(maxnum,ans);
}
cout<<maxnum<<endl;
return 0;
}
前缀和优化:O(n^2)
(用前缀和后数组就越界了)
int main() {
int n = 0; cin >> n;
int* a = new int[n];
cin>>a[0];
for (int i = 1; i < n; i++) {
cin >> a[i];
a[i] += a[i - 1];
}
int ans = 1 - a[0];
int temp = 0;
if (n == 2) {
if (a[1] == 2)cout << 1;
else cout << 2;
return 0;
}
//还有就是数组越界的问题,不得不分开讨论
for (int j = 0; j < n; j++) {
temp = a[n - 1] + j + 1 - 2 * a[j];
ans = max(ans, temp);
}
for(int i=1;i<n;i++)
for (int j = i; j <n; j++) {
temp = 2 * a[i - 1] + a[n - 1] + j + 1 - i - 2 * a[j];
ans = max(ans, temp);
}
cout << ans;
return 0;
}
动态规划:O(n)
value=原字符串值+翻转后的那一段
对于翻转,
0->1 , +1;
1->0 , -1
于是问题转化为连续字串的最大值
dp
当然啦,没必要搞个dp[i],再去求dp[i]的最大值
vector<int> b;
int main()
{
int n, temp, s = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> temp;
if (temp == 1)
{
s += 1;
b.push_back(-1);
}
else
{
b.push_back(1);
}
}
int curr_max = b[0];
int max_total = b[0];
for (int i = 1; i < n; i++)
{
curr_max = max(b[i], curr_max + b[i]);
max_total = max(curr_max, max_total);
}
cout << s + max_total;
return 0;
}