Optimizing Row with Maximum 1s in Binary Matrix

🚀 Day 49 of My Coding Journey Today I solved an interesting problem: Row with Maximum 1s in a Binary Matrix 🧠 Problem Insight: Given a 2D binary matrix where each row is sorted (0s first, then 1s), the goal is to find the index of the first row that contains the maximum number of 1s. ⚡ My Approach: At first, I thought of a brute force solution by counting 1s in every row. It works, but it's not efficient. Then I realized an important property: 👉 Since each row is sorted, once we find the first 1, all elements to the right are also 1. So instead of checking every element: Start from the top-right corner Move left if you find 1 Move down if you find 0 This reduces the time complexity to O(n + m) 🚀 💡 Key Learning: Understanding the structure of the data (sorted rows) can help optimize the solution drastically. 📌 Result: Successfully found the row index with maximum 1s efficiently. Every day, I’m getting better at recognizing patterns and optimizing solutions 💪 #Day49 #CodingJourney #Java #ProblemSolving #DataStructures #Algorithms #Learning #Consistency My way ===== // User function Template for Java class Solution {   public int rowWithMax1s(int arr[][]) {     int c=0,l=0,a=0;     for(int i=0;i<arr.length;i++)     {       for(int j=0;j<arr[i].length;j++)       {         if(arr[i][j]==1)         {           c++;         }       }       if(c>l)       {         l=c;         a=i;       }     c=0;     }     if(l>0)     {       return a;     }     else     {     return -1;     }   } }

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories