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.
1function minCostToMoveChips(position) {
2 let oddCount = 0, evenCount = 0;
3 for (let i = 0; i < position.length; i++) {
4 if (position[i] % 2 === 0) evenCount++;
5 else oddCount++;
6 }
7 return Math.min(oddCount, evenCount);
8}
9
10// Example usage
11console.log(minCostToMoveChips([1, 2, 3]));
This JavaScript solution iterates over each element in the array, checking for even or odd nature and increments the respective counter. The function returns the lesser value for cost computation.
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.
1#include <vector>
2using namespace std;
3
4int minCostToMoveChips(vector<int>& position) {
5 int count[2] = {0};
6 for (const auto& pos : position) {
7 count[pos % 2]++;
8 }
9 return min(count[0], count[1]);
10}
11
12// Example usage
13#include <iostream>
14int main() {
15 vector<int> position = {1, 2, 3};
16 cout << minCostToMoveChips(position) << endl;
17 return 0;
18}
Similar to the C solution, we maintain a count array to hold the frequency of even and odd positions. The use of modular arithmetic simplifies the index checks as whole numbers.