Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def _size_of_valley(valley: tuple) -> int:
- return valley[2] - valley[0] + 1
- def _is_valley_or_flat(valley: tuple, blocks: list) -> bool:
- if blocks[valley[1]] <= blocks[valley[0]] and blocks[valley[2]] >= blocks[valley[1]]:
- if blocks[valley[2] - 1] > blocks[valley[1]]:
- # Climbing upwards
- if blocks[valley[2]] >= blocks[valley[2] - 1]:
- return True
- else:
- return False
- else:
- # Going downards or staying flat
- return True
- else:
- return False
- def solution(blocks):
- """
- blocks which gives widest valley/flat shape will be the maximum distance
- Code is calculating widest valley/flat in linear time so that frogs can
- go two sides of the valley which would give maximum distance
- valley data structure => (beginning, deepest_point, end, size)
- """
- widest_valley = (0, 0, 0, 1)
- current_valley = (0, 0, 0, 1)
- # (point and height)
- flatness_beginning_point = (1, blocks[0])
- for i in range(1, len(blocks)):
- # Change deepest point if necessary
- if blocks[current_valley[1]] <= blocks[i]:
- tmp_valley = (current_valley[0], current_valley[1], i, current_valley[3] + 1)
- else:
- tmp_valley = (current_valley[0], i, i, current_valley[3] + 1)
- if _is_valley_or_flat(tmp_valley, blocks):
- current_valley = tmp_valley
- if blocks[i] != flatness_beginning_point[1]:
- flatness_beginning_point = (i, blocks[i])
- if _size_of_valley(widest_valley) < _size_of_valley(current_valley):
- widest_valley = current_valley
- else:
- if flatness_beginning_point[1] >= blocks[i]:
- current_valley = (flatness_beginning_point[0], i, i, 1)
- else:
- current_valley = (i, i, i, 1)
- return _size_of_valley(widest_valley)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement