The main observation here is that moving chips from position p to p+2 or p-2 incurs no cost. Hence, the cost to align all chips into one position is essentially the cost of moving all odd-indexed chips to even positions or vice versa.
To achieve this, count the number of chips at odd positions and the number of chips at even positions. The minimum cost to move all chips to the same position is the lesser of the two counts.
Time Complexity: O(n), where n is the number of chips.
Space Complexity: O(1) because only a fixed amount of extra space is used.
1#include <vector>
2using namespace std;
3
4int minCostToMoveChips(vector<int>& position) {
5 int oddCount = 0, evenCount = 0;
6 for (const auto& pos : position) {
7 if (pos % 2 == 0) evenCount++;
8 else oddCount++;
9 }
10 return min(oddCount, evenCount);
11}
12
13// Example usage
14#include <iostream>
15int main() {
16 vector<int> position = {1, 2, 3};
17 cout << minCostToMoveChips(position) << endl;
18 return 0;
19}
This C++ solution uses a similar logic as the C implementation, utilizing C++ vector for dynamic arrays and the min function to return the minimum of oddCount and evenCount.
A similar but slightly varied approach leverages modular arithmetic to classify indices. As the cost is incurred when moving by an odd number of steps, the strategy remains to count parity of indices and work from there.
Time Complexity: O(n) for iterating through the list of positions.
Space Complexity: O(1), with fixed space used to track counts.
1function minCostToMoveChips(position) {
2 const count = [0, 0];
3 for (let p of position) {
4 count[p % 2] += 1;
5 }
6 return Math.min(count[0], count[1]);
7}
8
9// Example usage
10console.log(minCostToMoveChips([1, 2, 3]));
This JavaScript solution uses a simple array and increment operators in a loop to track the counts of chip positions for evaluating minimum movement cost based on their parity status.