Monday, 5 February 2018

Counting Valleys Hacker Rank Solution in C

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

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int countingValleys(int n, char* s) {
    // Complete this function
      int c=0,v=0;
    for(int i=0;s[i] !='\0';i++)
    {
        if(s[i] == 'D')
            c--;
        else if(s[i] == 'U')
        {
            c++;
            if(c == 0 && s[i] == 'U')
                v++;
        }
           
    }
    return v;
}

int main() {
    int n;
    scanf("%i", &n);
    char* s = (char *)malloc(1000000 * sizeof(char));
    scanf("%s", s);
    int result = countingValleys(n, s);
    printf("%d\n", result);
    return 0;
}

1 comment:

  1. #include
    int main()
    {
    int a,c=0,i,p=0,n,min,max,xx[1000000];
    char y[1000000];
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    scanf("%s",&y[i]);

    }
    for(i=0;i<n;i++)
    {
    if(y[i]=='D'){
    --p;
    xx[i]=p;

    }


    else
    {
    ++p;
    xx[i]=p;


    }
    }
    xx[i]=0;
    for(i=0;i<n;i++){
    //printf("%d",xx[i]);
    if(xx[i]==0 && xx[i-1]<0){
    c++;

    }
    }
    printf("%d",c);
    }

    ReplyDelete