Moving by two is free, so all even positions are equivalent and all odd positions are equivalent. Pay to move the smaller parity group.
Complexity
O(n) time and O(1) space.
Find the minimum paid moves needed to bring all chips to one position under parity-based movement costs.
Moving by two is free, so all even positions are equivalent and all odd positions are equivalent. Pay to move the smaller parity group.
O(n) time and O(1) space.
package main
func minCostToMoveChips(position []int) int {
odd := 0
for _, value := range position {
odd += value % 2
}
even := len(position) - odd
if odd < even {
return odd
}
return even
}
class Solution:
def minCostToMoveChips(self, position: list[int]) -> int:
odd = sum(value % 2 for value in position)
return min(odd, len(position) - odd)
function minCostToMoveChips(position: number[]): number {
const odd = position.reduce((count, value) => count + (value % 2), 0);
return Math.min(odd, position.length - odd);
}