Sort by

recency

|

4160 Discussions

|

  • + 0 comments

    Great explanation of the Counting Valleys problem. I remember solving this when I was learning algorithms. By the way, if anyone is interested in the Free Fire Advance Server and wants to know how to register or get the latest updates, I’ve written a detailed guide here

  • + 0 comments

    ` function countingValleys(steps: number, path: string): number {

    let level = 0;
    let ans = 0;    
    
    for (let p of path) {
        if (p === 'D') {
            level --;
        } else if (p === 'U') {
            level ++;
        }
        if (level === 0 && p === 'U') {
            ans ++;
        }
    }
    return ans;
    

    }

  • + 0 comments
    public static int countingValleys(int steps, String path) {
            // Write your code here
            int difference = 0;
            boolean isValley = false;
            int count = 0;
            
            for (int i = 0; i < path.length(); i++) {
                if (difference == 0 && isValley) {
                    count++;
                }
                if (path.charAt(i) == 'U') {
                    if (difference == 0) {
                        isValley = false;
                    }
                    difference++;
                } else {
                    if (difference == 0) {
                        isValley = true;
                    }
                    difference--;
                }
            }
            
            if (isValley && difference == 0) {
                count++;
            }
            return count;
        }
    
  • + 0 comments

    **Logic to solve the problem is if the previous step was a "U" and the sealevel count becomes 0 it is a valley. **

            int sealevel = 0;
            int valley = 0;
            char[] charPath = path.toCharArray();
            for (int i = 0; i < steps ; i++) {
                if (charPath[i]=='U'){
                    sealevel++;
                    if(sealevel==0) valley++;
                } 
                if (charPath[i]=='D') sealevel--;
            }
            return valley;
        }
    }
    
  • + 0 comments
    def counting_valleys(steps, path):
        count = level = 0
        in_valley = False
        for i in range(steps):
            level += 1 if path[i] == "U" else -1
            if level == -1 and path[i] == "D" and not in_valley:
                count += 1
                in_valley = True
            if level == 0 and path[i] == "U" and in_valley:
                in_valley = False
        return count