Dynamic Programming Question:Hacker earth -October easy 2022
Q.You are given a binary string S of length N. A substring of a binary string is called positive if the number of 1′s present in the substring is strictly greater than the number of 0′s present. Find the number of positive substrings in the given string S Code: (Editorial Solution) # include<bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt--) { int n; cin >> n; string s; cin >> s; s = ')' + s; vector< int > pre(n + 1 ), dp(n + 1 ), pos( 2 * n + 1 , - 1 ); for ( int i = 1 ; i <= n; i++) { pre[i] = pre[i - 1 ] + (s[i] == '1' ? 1 : - 1 ); } pos[n] = 0 ; for ( int i = 1 ; i <= n; i++) { int idx = pos[pre[i] + n]; if (s[i] == '1' ) { if (idx == - 1 ) { dp[i] = i; } else { dp[i] = (i - idx - 1 ) + dp[idx]; } } else { if (idx != - 1 ) dp[i] = dp[idx]; } pos[pre[i] + n] = i; } cout << accumulate(dp.begin()...