You have n
chips, where the position of the i-th chip is position[i]
. You can perform two types of moves to move a chip:
x
to position x + 2
or x - 2
with no cost.x
to position x + 1
or x - 1
at a cost of 1.Return the minimum cost needed to move all the chips to the same position.
n
is the number of chips, and it is an integer where 1 <= n <= 100
.position
where 1 <= position[i] <= 10^9
.Given the operations allowed:
Key observations:
To minimize the cost, we can perform the following:
This is because we can freely move chips among odd or even positions without any cost, and ultimately, we only need to pay to switch the fewer group (either odd or even) to align with the majority.
def minCostToMoveChips(position):
odd_count = 0
even_count = 0
for pos in position:
if pos % 2 == 0:
even_count += 1
else:
odd_count += 1
# The minimum cost will be the minimal number of chips we have in either even or odd positions
return min(odd_count, even_count)
# Example usage:
position = [1, 2, 3] # Here is an example input
print(minCostToMoveChips(position)) # Expected output: 1
O(n)
where n
is the number of chips. We loop through the position list once to count the odd and even positioned chips.O(1)
since we only use two additional variables (odd_count
and even_count
) irrespective of the input size.This approach ensures that we find the optimal solution efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?