Problem Description
Given an array of chip positions, the task is to move all chips to the same position with minimum cost. Moving a chip by 2 units is free, while moving a chip by 1 unit costs 1. The goal is to minimize the total cost to align all chips.
Key Insights
- Moving a chip by 2 units does not incur any cost, so chips can be moved freely between positions of the same parity (even or odd).
- The cost only occurs when moving chips between positions of different parity.
- The optimal strategy is to move all chips to a position with the parity that already has the most chips, incurring the cost on the fewer chips from the opposite parity.
Space and Time Complexity
Time Complexity: O(n), where n is the number of chips. Space Complexity: O(1), since only a constant amount of extra space is used.
Solution
Since moving chips by 2 units is free, you can bring all chips to any position that shares their parity without cost. Therefore, the problem reduces to deciding whether to move all chips to an even position or an odd position. The total cost is equal to the number of chips in the smaller group (either odd or even) because each chip in the minority group will require a single move costing 1 to switch parity. Thus, the solution is to count the chips in even and odd positions and return the minimum count.