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.
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
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)
}
}
Please feel free to share your comments.
Happy reading!!!
Top comments (0)