did test def pick(matrix): max_v = -0x80000000 for y in range(len(matrix)): dp = [[0]*len(matrix[0]) for _ in matrix] r = pick_strawberry(dp, matrix, y, 0, 0) if r > max_v: max_v = r return max_v def pick_strawberry(dp, matrix, start_y, x, curr): if x >= len(matrix[0]): return for target_y in range(len(matrix)): y = start_y sum_v = curr while y != target_y: if matrix[y][x] == 0: dp[target_y][x] = 0 else: sum_v += matrix[y][x] if y == len(len(matrix)): sum_v = 0 y = (y+1)%len(len(matrix)) dp[target_y][x] = sum_v + matrix[target_y-1][x] while y != target_y: if matrix[y][x] == 0: dp[target_y][x] = max(dp[target_y][x], 0) else: sum_v += matrix[y][x] if y == -1: sum_v = 0 y = (y+len(matrix))%len(len(matrix)) dp[target_y][x] = max(dp[target_y][x], sum_v + matrix[target_y+1][x]) for y in range(len(matrix)): pick_strawberry(matrix, y, x+1, curr) return max([matrix[y][len(matrix[0]-1)] for y in range(len(matrix))])