File tree 1 file changed +7
-3
lines changed
1 file changed +7
-3
lines changed Original file line number Diff line number Diff line change @@ -5,16 +5,20 @@ def read_input(textio: TextIO) -> List[int]:
5
5
positions = [int (num ) for num in textio .readlines ()[0 ].split (',' )]
6
6
return positions
7
7
8
- def cost (positions :List [int ], target_position :int ) -> int :
9
- return sum (abs (position - target_position ) for position in positions )
8
+ def cost (position : int , target_position : int ) -> int :
9
+ diff = abs (position - target_position )
10
+ return int ((diff + 1 )* diff / 2 )
11
+
12
+ def total_cost (positions :List [int ], target_position :int ) -> int :
13
+ return sum (cost (position , target_position ) for position in positions )
10
14
11
15
def find_cheapest (positions :List [int ]):
12
16
min_pos = min (positions )
13
17
max_pos = max (positions )
14
18
15
19
costs = dict ()
16
20
for pos in range (min_pos , max_pos + 1 ):
17
- costs [pos ] = cost (positions , pos )
21
+ costs [pos ] = total_cost (positions , pos )
18
22
19
23
min_cost_pos = min (costs , key = costs .get )
20
24
return min_cost_pos , costs [min_cost_pos ]
You can’t perform that action at this time.
0 commit comments