Counting Valleys

  • + 0 comments

    A rust solution:

    fn countingValleys(steps: i32, path: &str) -> i32 {
        let (_, valley) = path.bytes()
            .fold((0, 0), |mut acc, step| {
                if acc.0 == -1 && step == b'U' {
                    acc.1 += 1;
                }
                
                if step == b'U' { 
                    acc.0 += 1
                } else if step == b'D' { 
                    acc.0 -= 1;
                }
                
                acc
            });
        valley
    }