Advertisement
ikseek

Untitled

Aug 5th, 2021 (edited)
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. from collections import namedtuple
  2. from functools import cache
  3. from itertools import groupby
  4. from typing import List
  5.  
  6. BoxRun = namedtuple("Box", ("color", "count"))
  7.  
  8.  
  9. class Solution:
  10.     def removeBoxes(self, boxes: List[int]) -> int:
  11.         @cache
  12.         def best_score(boxes, same_as_first_around):
  13.             # Try to take same boxes from the left
  14.             lead_color = boxes[0].color
  15.             same_as_first_around += boxes[0].count
  16.             boxes = boxes[1:]
  17.             # And from the right if they are the same color
  18.             if boxes and boxes[-1].color == lead_color:
  19.                 same_as_first_around += boxes[-1].count
  20.                 boxes = boxes[:-1]
  21.             if not boxes:  # We took last boxes, just count the points
  22.                 return same_as_first_around ** 2
  23.             else:
  24.                 # Assume there are no same-color boxes in between
  25.                 score = same_as_first_around ** 2 + best_score(boxes, 0)
  26.                 for mid in range(1, len(boxes)):
  27.                     # Scan boxes in between looking for same colored boxes
  28.                     if boxes[mid].color == lead_color:
  29.                         # Check if removing boxes to the left first improves the score
  30.                         score_for_removed = best_score(boxes[:mid], 0)
  31.                         score_for_joined = best_score(boxes[mid:], same_as_first_around)
  32.                         score = max(score, score_for_removed + score_for_joined)
  33.                 return score
  34.  
  35.         box_runs = tuple(BoxRun(color, len(list(run))) for color, run in groupby(boxes))
  36.         return best_score(box_runs, 0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement