DEV Community

Sivakumar
Sivakumar

Posted on • Edited on

2 1

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!!!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay