Jump Game II in Rust

impl Solution {
    pub fn jump(nums: Vec<i32>) -> i32 {
        let mut jumps = 0; // Number of jumps needed
        let mut current_jump_end = 0; // End of the range that can be reached with current number of jumps
        let mut farthest = 0; // Farthest point that can be reached

        // Iterate over the array except for the last element
        for i in 0..nums.len() - 1 {
            // Update the farthest point that can be reached
            farthest = std::cmp::max(farthest, i + nums[i] as usize);

            // If reached the end of the current jump, increase the jump count and update current jump end
            if i == current_jump_end {
                jumps += 1;
                current_jump_end = farthest;
            }
        }

        jumps
    }
}

PrevNext