DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Sivakumar
Sivakumar

Posted on • Updated on

Data Structures & Algorithms using Rust: Max Consecutive Ones

As part of Data Structures and Algorithms implementation using Rust, today we will explore Max Consecutive Ones problem.

Leetcode problem link: https://leetcode.com/problems/max-consecutive-ones/

Problem Statement
Given a binary array, find the maximum number of consecutive 1s in this array.
Enter fullscreen mode Exit fullscreen mode
Instructions
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.
Note:

The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
Enter fullscreen mode Exit fullscreen mode
Solution

Here is my solution to above problem

use std::cmp;

impl Solution {
    pub fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
        let mut i_max: i32 = 0;
        let mut i_cnt: i32 = 0;
        for i in 0..nums.len() {
            let t = nums[i];
            if t == 0 {
                i_max = cmp::max(i_cnt, i_max);
                i_cnt = 0;
            }
            i_cnt += t;
        }
        cmp::max(i_cnt, i_max)
    }
}
Enter fullscreen mode Exit fullscreen mode

Please feel free to share your comments.

Happy reading!!!

Top comments (0)

🌚 Life is too short to browse without dark mode