algorithm - Finding largest element in matrix B, better than O(n)? Practice Tech Interview -


suppose have matrix b, size n n, distinct integer elements. local maximum exists if greater of neighbors (diagnols too). suppose b has 1 local maximum , each column of b has local maximum. show can find local maximum of b in better o(n).

my attempt: imagine line "suppose b has 1 local maximum" meant tell me positioning (ordering?) of elements, can seem grasp head around it. fact better o(n) constraint tells me peak finding divide , conquer ( o(logn*logn) ?) approach, not sure recurse upon.

i think can done in o(n).

see question says 1 global maximum (i.e 1 local maximum whole matrix) , each column has local maximum.

  1. start first column , find out local maximum(say @ (i,j)). check if global maximum or not.

  2. if not global maximum has local maximum in next column in adjacent cells((i,j+1),(i-1,j+1) & (i+1,j+1) if these cells exist) greater current local maximum.

now repeat these steps , in each steps find local maximum next column in constant time( need compare 3 cells specified in step 2) , maximum no. of columns needed searched = n(worst case global maximum found in last column).

so, total complexity o(n).


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -