B: Maximum Substring
A binary string is a string consisting only of the characters 0 and 1. You are given a binary string s.
For some non-empty substring of string containing characters 0 and characters 1, define its cost as:
- , if and ;
- , if and ;
- , if and .
Given a binary string of length , find the maximum cost across all its non-empty substrings.
A string is a substring of a string if can be obtained from by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Each test consists of multiple test cases. The first line contains a single integer () — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer () — the length of the string .
The second line of each test case contains a binary string of length .
It is guaranteed that the sum of over all test cases does not exceed .
For each test case, print a single integer — the maximum cost across all substrings.
Solution:
- #include <bits/stdc++.h>
- using namespace std;
- int twos(int a)
- {
- int count = 0;
- while (a % 2 == 0 && a > 0)
- {
- a = a / 2;
- count++;
- }
- return count;
- }
- int main()
- {
- int t;
- cin >> t;
- while (t--)
- {
- int n;
- cin >> n;
- string s;
- cin >> s;
- int zero = 0, one = 0, num1 = 0, num0 = 0;
- int i = 0, j = 0;
- while (i < n)
- {
- if (s[i] == '0')
- {
- int count1 = 0;
- while (s[i] == '0' && i < n)
- {
- num0++;
- i++;
- count1++;
- }
- zero = max(zero, count1);
- }
- i++;
- }
- while (j < n)
- {
- if (s[j] == '1')
- {
- int count2 = 0;
- while (s[j] == '1' && j < n)
- {
- num1++;
- j++;
- count2++;
- }
- one = max(one, count2);
- }
- j++;
- }
- // cout << num1 << " " << num0 << " " << zero << " " << one << endl;
- cout << max((long long int)num1 * (long long int)num0, max((long long int)one * (long long int)one, (long long int)zero * (long long int)zero)) << endl;
- }
- }
Comments
Post a Comment