Java

Moderators: zibadian
Number of threads: 7818
Number of posts: 18218

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Largest number of integers in a row within an array Posted by nippy on 25 Oct 2010 at 8:03 AM
I an Integer array with only ones and zeros. What would be the Simplest way to count the largest row of zeros that appear within that array. Such as if there was 5 zeros back to back at the beginning of the array and another 7 zeros in a row at the end of the array. that answer would be seven.
Im assuming there would have to be a way to compare the last stored highest number and the newest.

Thanks for anyhelp given.
Report
Re: Largest number of integers in a row within an array Posted by Josh Code on 3 Nov 2010 at 1:44 PM
That problem is closely related to finding the maximum number within an array. It can be done sequentially in O(n) time where n is proportional to length of array.


This method wasn't tested by compiling and running but it might work and is definitely close to what you want:
int getLengthOfMaximumSequenceOfZeros(int a[])
{

int maxLen=0;
int curLen=0;

// loop through all elements in the array.
for (int i=0;i<a.length;i++)
{
  if (a[i]==0)
  {
     curLen++; // sequence is getting longer by 1.
  }
  else // restarting new sequence of zeros
  {
    // if the sequence ending is longer, remember its length.
    if (curLen>maxLen) 
       maxLen = curLen;

    curLen=0; // current sequence has length 0 again.
  }
}
// if longest sequence goes right to the end of array
if (curLen>maxLen) 
   maxLen = curLen;

return maxLen;
}



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.