In article <5f5518d0.0310030628.538897a3@posting.google.com >,
sfrazq@hotmail.com says...[color=blue]
> Hi,
> I have an nxn array in which in each row is consisting of +ve and -ve
> numbers, such that -ve number comes before +ve numbers. e.g.
>
> -45 | -9 | -3 | 2
> ===================
> -5 | -9 | 21 | 12
> ===================
> -4 | 19 | 18 | 5
> ===================
> -15 | -17 | 38 | 3
>
> all I have to do is to find the row with max number of +ve integers.
> in the above case 3rd row.
>
> My problem is that I have to make algorithm linear i.e. O(n) instead
> of O(n^2).
> any sugestions.[/color]
I suspect you'll get more help in a newsgroup devoted to algorithms than
one devoted to a language.
My immediate guess is that it's not possible to make it linear on N.
Making it O(N lg N) is fairly straightforward, but unless there's more
organization to the numbers than you've said, making it O(N) shouldn't
be possible.
My reasoning is as follows: you've said nothing about a relationship
between rows, so you apparently need to search all the rows. That's
clearly O(N) by itself. For the overall algorithm to remain O(N), you'd
have to search each row in constant time. TTBOMK, that's just not
possible; O(Lg2 N) is the best that's known (i.e. a binary search for
the first positive number in the row).
If the numbers you posted are representative, there may be a possibility
though: in the numbers you gave, the position of the first +ve in any
given row differs from the one in the previous row by no more than one
position.
If that is always the case, then you can do an O(Lg2 N) search for the
first +ve in the first row, and then search through only three numbers
for each consecutive row to find it.
I have no idea whether that's always the case or not though -- it may be
purely an accident that the numbers you posted happen to follow this
particular pattern.
--
Later,
Jerry.
The universe is a figment of its own imagination.