[
math
array
greedy
]
Leetcode 1217. Minimum Cost to Move Chips to The Same Position
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position
Quite easy problem when you undrstand what you need to do. So, we have chips on different positions, and we can move them for free in +2
and -2
positions: it means, that we can for free move all chips with odd positions to one odd position and chips with even positions to one even positions. Moreover, we can make these odd and even positions adjacent. So, what we need to do now is just calculate how many we have on even positions and on odd positions and choose the smallest number.
Complexity: time complexity is O(n)
, we just iterate our numbers once, space complexity is O(1)
.
class Solution:
def minCostToMoveChips(self, P):
return min((odd := sum(1 for p in P if p%2)), len(P) - odd)
If you like the solution, you can upvote it on leetcode discussion section: Problem 1217