Counting Valleys - HackerRank || HackerRank Counting Valleys Solution

Problem Name: Counting Valleys
Judge: HackerRank
Problem link: Counting Valleys



HackerRank Counting Valleys Solution in C

#include <stdio.h>

int main()
{
    int n, i, count = 0, result = 0;
    scanf("%d", &n);
    char valleys;
    for (i = 1; i <= n; i++)
    {
        scanf("%c", &valleys);
        if (valleys == 'U') count++;
        else if (valleys == 'D') count--;
        if (count == 0 && valleys == 'U') result++;
    }
    printf("%d\n", result);

    return 0;
}


HackerRank Counting Valleys Solution in C++/Cpp

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, i, count = 0, result = 0;
    cin >> n;
    char valleys;
    for (i = 0; i < n; i++)
    {
        cin >> valleys;
        if (valleys == 'U') count++;
        else if (valleys == 'D') count--;
        if (count == 0 && valleys == 'U') result++;
    }
    cout << result << endl;

    return 0;
}


HackerRank Counting Valleys Solution in Java

import java.util.Scanner;

public class Counting_Valleys {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        input.nextLine();
        int counter = 0, total = 0;
        String valleys = input.nextLine();
        Character c1 = 'U', c2 = 'D';
        for (int i = 0; i < valleys.length(); i++) {
            char c = valleys.charAt(i);
            if (c1.equals(c)) counter++;
            else if (c2.equals(c)) {
                counter--;
                if (counter == -1) total++;
            }
        }
        System.out.print(total);
    }
}





Next Post Previous Post
No Comment
Add Comment
comment url