对于一个长度为n,且只由0和1构成的字符串s,定义一个相邻数对(i,i+1),当si=0且s(i+1)=1的时候,称其为零一数对。…
- User
对于一个长度为n,且只由0和1构成的字符串s,定义一个相邻数对(i,i+1),当s_i=0且s_(i+1)=1的时候,称其为零一数对。 现在至多选择一个区间l,r,选择区间内的每一个字符反置。 问:经过修改后(也可以不修改)的字符串最多能有多少个零一数对?
若当前字符为0,反置后为1;若当前字符为1,反置后为0。
输入描述 第一行输入一个整数n(1≤n≤10^5),表示字符串的长度。第二行输入一个长度为n,且只由0和1构成的字符串s。
输出描述 在一行上输出一个整数,代表最多的零一数对数量。
示例1 输入 7 1010010 输出 3 说明 选择翻转区间[1,4],翻转后字符串s=0101010,一共有三个零一数对。可以证明这是最多的方案。
- Assistant
To solve this problem, we need to determine the maximum number of "zero-one pairs" that can be achieved by flipping at most one consecutive interval in the given binary string.
Firstly, we need to understand what causes the number of zero-one pairs to change when we flip a segment:
- Flipping affects the pairs at the boundaries of the flipped segment, i.e., positions
l-1andr(if they exist). - Flipping the segment can increase the number of zero-one pairs by at most 2 because only the pairs at
l-1andrcan change from not being zero-one pairs to being zero-one pairs.
Given this, we can deduce that:
- The maximum increase in the number of zero-one pairs is 2.
- The total number of zero-one pairs cannot exceed
n - 1, where is the length of the string because there are only pairs in total.
- Flipping affects the pairs at the boundaries of the flipped segment, i.e., positions