0-1翻转 Flipping Game

题目描述如下:
在这里插入图片描述
暴力枚举: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值