Counting Valleys

Problem

Solution

import java.io.IOException;

class Result {
    public static int countingValleys(int steps, String path) {
        int valleyCount = 0, prePos, pos = 0;
        for (int i = 0; i < steps; i++) {
            prePos = pos;
            if (path.charAt(i) == 'D')
                pos--;
            else
                pos++;
            if (pos == 0 & prePos < 0)
                valleyCount++;
        }
        return valleyCount;
    }
}

public class CountingValleys {
    public static void main(String[] args) throws IOException {
        int steps = 8;
        String path = "UDDDUDUU";
        int result = Result.countingValleys(steps, path);
        System.out.println(result);
    }
}

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *