Posts

Showing posts from October, 2022

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()...

Greedy Algorithm Problem: Geek collects the balls

 I haven't posted for a while, 8 months to be precise. I am practicing DSA nowadays after a lot of soul searching. My plans have taken a left turn very wildly. Hope I achieve my goals.... I do have backup plans so hope that it keeps me in safe position Anyways, I came upon this question in Geeks for Geeks portal. Its a medium-level problem. So I found that ,for this question there were no articles or videos giving the correct solution that works in GFG portal and successfully runs all testcases. There is a GFG video but while its core logic is correct, it doesn't take into account all the different possibilities of solving each testcase so their code doesn't work Here is the link to the GFG video: Video link for problem Problem statement: There are two parallel roads, each containing  N  and  M  buckets, respectively. Each bucket may contain some balls. The balls in first road are given in an array  a  and balls in the second road in an array  b ....