Luogu P5650 贪心90分

问题遇到的现象和发生背景

Luogu P5650

img

反复检查,不知道为什么错一个点。

用代码块功能插入代码,请勿粘贴截图
// Author:PanDaoxi
#include 
#define int long long
using namespace std;

int n, len, a, b;
string s;

signed main(){
    ios :: sync_with_stdio(false);
    
    cin >> s;
    len = s.size();
    for(int i=0; iif(s[i] == '0'){
            b = max(++a, b);
        }
        else{
            a = max(0ll, a-1);
        }
    }
    cout << b;
    
    return 0;
}
我的解答思路和尝试过的方法

贪心。

令 a=当前最优解 b=全局最优解
遇到0:a+1和b取较大值,更新b。
遇到1:a-1和0取较大值,更新a。
最后输出全局最优解。

求指点。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
string s;
int main()
{
    int ans=-1,num=0;
    std::ios::sync_with_stdio(0);
    cin>>s;
    for(int i=0;i<s.size();++i)
    {
        int t=s[i]-'0';
        if(t==0) num++,ans=max(ans,num);
        else     num--,num=max(0,num);
    }
    cout<<ans<<endl;
    return 0;
}