Last active
July 31, 2018 02:18
-
-
Save OzuYatamutsu/bcf6ddac0d15059581023a3c40b71df9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
def find_max_area(heights: list, debug=False) -> int: | |
Point = namedtuple('Point', ['x', 'y']) | |
distance = lambda p2, p1: p2.x - p1.x if p2.x >= p1.x else p1.x - p2.x | |
move_point = lambda point, increment: Point(point.x + increment, heights[point.x + increment]) | |
# Calculate area based on distance between lowest heights. | |
calc_max_area = lambda p2, p1: min(p2.y, p1.y) * distance(p2, p1) | |
# Initialize two pointers on either ends of the height list. | |
left_point, right_point = Point(0, heights[0]), Point(len(heights) - 1, heights[-1]) | |
max_area = calc_max_area(left_point, right_point) | |
# ...and move 'em towards each other! | |
while left_point.x != right_point.x: | |
max_area = max(max_area, calc_max_area(left_point, right_point)) | |
print( | |
"Current positions: " | |
f"Left point@({left_point.x}, {left_point.y}), " | |
f"Right point@({right_point.x}, {right_point.y}) " | |
f"(Max area is {max_area}.)\n" if debug else "", end='' | |
) | |
# If one side's height is lower than the other, that height may | |
# have room to improve. Move it towards the greater one. | |
if left_point.y < right_point.y: | |
left_point = move_point(left_point, 1) | |
else: | |
right_point = move_point(right_point, -1) | |
return max_area |
Author
OzuYatamutsu
commented
Jul 31, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment