Skip to content

Instantly share code, notes, and snippets.

@vishoo7
Last active April 10, 2017 01:47
Show Gist options
  • Save vishoo7/51dbf0af1ed5cd0a7f6ca9a75bc3daa8 to your computer and use it in GitHub Desktop.
Save vishoo7/51dbf0af1ed5cd0a7f6ca9a75bc3daa8 to your computer and use it in GitHub Desktop.
Here's a recent interview problem. Find the walk from the top left to the bottom right that maximizes the minimum element traveled. I believe I have the brute force solution and the most efficient solution.
import sys
def find_max_min_brute(array, x=0, y=0):
max_x = max_y = len(array) - 1
current = array[y][x]
if x == max_x and y == max_y:
return current
if x == max_x:
return min(current, find_max_min_brute(array, x, y + 1))
if y == max_y:
return min(current, find_max_min_brute(array, x + 1, y))
return max(min(current, find_max_min_brute(array, x + 1, y)), \
min(current, find_max_min_brute(array, x, y + 1)))
def find_max_min_helper(array, row, col):
max_child = None;
if col < len(array) - 1:
max_child = find_max_min_helper(array, row, col + 1);
if row < len(array) - 1:
next_row_min = find_max_min_helper(array, row + 1, col)
if max_child:
max_child = max(next_row_min, max_child)
else:
max_child = next_row_min;
return min(array[row][col], max_child or sys.maxsize);
def find_max_min(array):
if len(array) == 0:
return None
return find_max_min_helper(array, 0, 0)
a = [[5, 4], [2, 5]]
b = [[9, 4, 8], [6, 5, 6], [3, 2, 9]]
c = [[9, 2, 7], [6, 5, 8], [8, 9, 10]]
d = [[1]]
print(find_max_min_brute(a))
print(find_max_min_brute(b))
print(find_max_min_brute(c))
print(find_max_min_brute(d))
print(find_max_min(a))
print(find_max_min(b))
print(find_max_min(c))
print(find_max_min(d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment