873B - Balanced Substring - CodeForces Solution


dp implementation *1500

Please click on ads to support us..

Python Code:

from itertools import accumulate
n,s = int(input()),[*accumulate(map(lambda x: 2*int(x)-1,input()))]
l = {0:-1}; c = 0
for x,y in enumerate(s):
    l[y]=e=l.get(y,x)
    c = max(c,x-e)
print(c)

C++ Code:

//بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيمِ
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
template<typename T> using ordered_set = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define Samo7a ios_base::sync_with_stdio(false);cin.tie(nullptr); cout.tie(nullptr);
#define re return
#define FX(n) fixed << setprecision(n)
#define endl '\n'
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define pb push_back
#define eb emplace_back
#define pi acos(-1)
#define F first
#define S second
const int N = 2e3 + 10, MOD = 1e9 + 7;
const int dx[]{1, -1, 0, 0, 1, -1, 1, -1};
const int dy[]{0, 0, 1, -1, 1, -1, -1, 1};

inline void debugMode() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
}

//الشَّيْطَانُ يَعِدُكُمُ الْفَقْرَ وَيَأْمُرُكُم بِالْفَحْشَاءِ ۖ وَاللَّهُ يَعِدُكُم مَّغْفِرَةً مِّنْهُ وَفَضْلًا ۗ وَاللَّهُ وَاسِعٌ عَلِيمٌ (268)
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//
/*
 id:
 idea:
 */




void TestCase() {
    int n;
    string s;
    cin >> n >> s;
    map < int , int > mp;
    mp[0] = 0;
    int delta = 0;
    int mx = 0;
    for ( int i = 0 ; i < n ; i++)
    {
        (s[i] == '1')?delta++: delta--;
        if (not mp.count(delta))
            mp[delta] = i + 1;
        else
            mx = max(mx , (i + 1) - mp[delta]);
    }
    cout << mx << endl;
}

int main() {
    Samo7a
    debugMode();
    int t = 1;
    //cin >> t;
    while (t--) {
        TestCase();
    }
    re 0;
}


Comments

Submit
0 Comments
More Questions

198. House Robber
153. Find Minimum in Rotated Sorted Array
150. Evaluate Reverse Polish Notation
144. Binary Tree Preorder Traversal
137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder