版权声明:本文作者靖心,靖空间地址:http://blog.csdn.net/kenden23/。未经本作者同意不得转载。 https://blog.csdn.net/kenden23/article/details/24862445

Iahub got bored, so he invented a game to be played on paper.

He writes n integers a1, a2, ..., an.
Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n)
and flips all values ak for
which their positions are in range[i, j] (that is i ≤ k ≤ j).
Flip the value of x means to apply operation x = 1 - x.

The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.

Input

The first line of the input contains an integer n (1 ≤ n ≤ 100).
In the second line of the input there are n integers:a1, a2, ..., an.
It is guaranteed that each of those n values is either 0 or 1.

Output

Print an integer — the maximal number of 1s that can be obtained after exactly one move.

Sample test(s)
input
5
1 0 0 1 0
output
4

本题由于数据量小,能够使用暴力法,时间效率是O(n^3)

可是这里巧用最大子段和的思想。能够把时间效率降到O(n)

思想:

1 想使用一个新的数列,计算连续出现了多少个1和连续出现了多少个零

2 求这个新数列的最大子段和

3 Flip最大子段中的 0 和 1,

4 计算出结果

比暴力法复杂非常多了,可是时间效率却提高了三个档次。

#include <vector>
#include <string>
#include <iostream>
using namespace std; void FlippingGame()
{
int n, a;
cin>>n;
vector<bool> vbn(n);
for (int i = 0; i < n; i++)
{
cin>>a;
vbn[i] = a;
}
vector<int> ans;
int c = 1;
for (int i = 1; i < n; i++)
{
if (vbn[i] == vbn[i-1]) c++;
else
{
if (vbn[i-1]) ans.push_back(-c);
else ans.push_back(c);
c = 1;
}
}
if (vbn.back()) ans.push_back(-c);
else ans.push_back(c); //求最大子段和思想
int stTmp = 0, st = ans.size(), end = ans.size(), maxVal = 0, sum = 0;
for (unsigned i = 0; i < ans.size(); i++)
{
sum += ans[i];
if (sum > maxVal)
{
st = stTmp;
maxVal = sum;
end = i;
}
if (sum <= 0)
{
sum = 0;
stTmp = i+1;
}
} int nums = 0;
for (int i = 0; i < ans.size(); i++)
{
if (ans[i] < 0) nums += ans[i];
}
if (maxVal > 0) cout<<maxVal - nums;
else cout<<-(ans.front()+1);
}

最新文章

  1. LeetCode题解-----Wildcard Matching
  2. lua class(table)
  3. js表单操作
  4. Pike学习笔记
  5. activiti自定义流程之Spring整合activiti-modeler5.16实例(九):历史任务查询
  6. java利用反射绕过私有检查机制实行对private、protected成员变量或方法的访问
  7. java数组使用技巧
  8. oschina程序开发
  9. OutputDebugString输出调试信息到debugtrack
  10. first os
  11. iOS 开发之Block
  12. 徒手用Java来写个Web服务器和框架吧&lt;第二章:Request和Response&gt;
  13. selenium调用webdriver异常
  14. What&#39;s news in Visual Studio 2017
  15. 深入理解JVM(2)——揭开HotSpot对象创建的奥秘
  16. selenium之调用Javascript
  17. python自定义函数的参数之四种表现形式
  18. bzoj 4084 双旋转字符串
  19. 【题解】Luogu P3950 部落冲突
  20. 警惕ASP.NET MVC中的ValidateInputAttribute

热门文章

  1. 正排索引(forward index)与倒排索引(inverted index)
  2. 原创:微信小程序亲测体验,公众号入口曝光!
  3. [转]JavaScript和html5 canvas生成圆形印章
  4. vue加载Element ui地址省市区插件-- element-china-area-data
  5. 对象和类型(数组、ref、out)
  6. js扩展
  7. MDI-设置子窗体只能弹出一个--单例模式
  8. 用c+libcurl+PCRE写爬虫2--好用的正则表达式
  9. Linux终端和win32控制台文本颜色输出
  10. hdu 1565 方格取数(1) 状态压缩dp