A local maximum in a 2D array can be defined as a value such that all it\'s 4 neighbours are less than or equal to it, ie, for a[i][j]
to be a local maximum,
Unless your array is square, your solution is actually O(I * J)
not O( n^2 )
. Strictly speaking you only have N
elements in your 2d array thus this solution is O(N)
. The only way it could be O( n^2 )
is if the array was square such that I = J = N
.
Since the compare is <=
rather than <
, you need still need to check the next element any shortcuts you try will likely be processor specific.
The worst case is that the entire array is a local maxima because the entire array equals the same value.
Thus you must visit every element once, making it O(N)
To improve real world performance in this you would need to use pointers to access you array as in most languages 2d arrays perform considerably worse than 1d arrays.