Solution to the problem 'Counting Valleys' from HackerRank

 question link: https://www.hackerrank.com/challenges/counting-valleys/problem

#include <bits/stdc++.h>
#define int long long
#define pb push_back
#define fi first
#define se second
#define pii pair<int,int>
using namespace std;

int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n,ans=0;
    cin>>n;
    vector<int> hike;
    int prefix[n];
    for(int i=0;i<n;i++){
        char a;
        cin>>a;
        if(a=='U') hike.pb(1);
        else hike.pb(-1);
    }
    prefix[0]=hike[0];
    for(int i=1;i<n;i++) prefix[i]=prefix[i-1]+hike[i];
    for(int i=1;i<n;i++){
        if(prefix[i]==0&&prefix[i-1]==-1) ans++;
    }
    cout<<ans;
    return 0;
}

Comments

Popular posts from this blog

Solution of 'The Two Dishes' (Codechef)

Solution of 'Tom Riddle's Diary' (Codeforces)

Solution of 'Less or Equal' (Codeforces)