惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
J
Java Code Geeks
腾讯CDC
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
美团技术团队
L
LangChain Blog
WordPress大学
WordPress大学
A
About on SuperTechFans
Martin Fowler
Martin Fowler
月光博客
月光博客
Y
Y Combinator Blog
U
Unit 42
D
Docker
Recent Announcements
Recent Announcements
Hugging Face - Blog
Hugging Face - Blog
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
G
Google Developers Blog
Last Week in AI
Last Week in AI
T
The Blog of Author Tim Ferriss
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Max Consecutive Ones
Jaspreet singh · 2026-06-15 · via DEV Community

Jaspreet singh

Problem Statement

Given a binary array nums, return the maximum number of consecutive 1's present in the array.

Example

Input:

nums = [1,1,0,1,1,1]

Output:

3

Explanation:

The longest sequence of consecutive 1's is [1,1,1]
Length = 3


Brute Force Intuition (Interview Explanation)

For every index, if the element is 1, start moving forward and count how many consecutive 1's exist.

Keep updating the maximum length found so far.

Since for every position we may scan ahead again, many elements get visited multiple times.

Time Complexity

O(N²)

Space Complexity

O(1)

Brute Force Java

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {

        int maxLen = 0;

        for (int i = 0; i < nums.length; i++) {

            int count = 0;

            for (int j = i; j < nums.length; j++) {

                if (nums[j] == 1) {
                    count++;
                    maxLen = Math.max(maxLen, count);
                } else {
                    break;
                }
            }
        }

        return maxLen;
    }
}


Moving Towards Optimal

Notice that we only need the length of the current streak of 1's.

Whenever we encounter:

  • 1 → extend the current streak.
  • 0 → streak breaks, reset count.

Thus, a single traversal is enough.

No extra data structure is required.


Optimal Approach – Running Count

Algorithm

  1. Initialize:
    • curCount = 0
    • maxCount = 0
  2. Traverse the array.
  3. If current element is 1:
    • Increment curCount
    • Update maxCount
  4. If current element is 0:
    • Reset curCount = 0
  5. Return maxCount.

Why It Works

A consecutive sequence continues only while we keep seeing 1's.

Whenever a 0 appears, the sequence breaks and a new count must start after it.

So maintaining only the current streak length is sufficient.


Optimal Java Solution

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {

        int maxCount = 0;
        int curCount = 0;

        for (int num : nums) {

            if (num == 1) {
                curCount++;
                maxCount = Math.max(maxCount, curCount);
            } else {
                curCount = 0;
            }
        }

        return maxCount;
    }
}


Dry Run

Input:

nums = [1,1,0,1,1,1]

Element Current Count Max Count
1 1 1
1 2 2
0 0 2
1 1 2
1 2 2
1 3 3

Final Answer:

3


Pattern Recognition

This pattern appears whenever the problem asks for:

  • Longest consecutive occurrence
  • Longest streak
  • Continuous segment
  • Maximum run length

Common approach:

Maintain Current Streak
Update Global Maximum
Reset on Break Condition

Examples:

  • Max Consecutive Ones
  • Longest Increasing Continuous Segment
  • Longest Repeating Character Block
  • Continuous Attendance/Activity Problems

Interview One-Liner

Since only the current streak of consecutive 1's matters, we maintain a running count, reset it whenever a 0 appears, and continuously update the maximum streak, achieving O(N) time and O(1) space.