I have a table of dimension m * n as given below
2 6 9 13
1 4 12 21
10 14 16 -1
Few constraints about this table:
- Elements in each row is sorted in increasing order (natural
ordering). - A -1 means the cell is of no significance for the purpose of
calculatio, i.e. no element exists there. - No element can appear in a row after a -1.
- All the cells can have either a positive number between 0 and N or
a -1. - No two cells have the same positive numbe, i.e. a -1 can appear
multiple times but no other number can.
Question: I would like to find a set S of n numbers from the table where the set must contain only one number from each row and the max(S) – min(S) is as small as possible.
For e.g. the above table gives me S = 12,13,14.
I would really appreciate if this can be solved. My solution is complicated and it takes O(m^n) and this is too much. I want an optimal solution.
Time complexity is O(m*n*log(m)).