CP01 Editorial

Problem Link

Click here

Difficulty level

Easy

Solution

It is always optimal to create a partition as small as possible in which ‘1’ appears exactly once more than ‘0’. So if cnt1 is the number of times ‘1’ appears in s and cnt0 is the number of times ‘0’ appears in s, then our answer will be cnt1-cnt0.

Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int T;
	cin>>T;
	while(T--)
	{
		string s;
		cin>>s;
		int n=s.length();
		int cnt1=0,cnt0=0;
		for(int i=0; i<n; i++){
			if(s[i]=='1')
			 cnt1++;
			else
			 cnt0++;
		}
		int var=cnt1-cnt0;
		cout<<cnt1-cnt0<<"\n";
	}
	return 0;
}