Leetcode 1217. Minimum Cost to Move Chips to The Same Position
You are given an array position
of integers. Here, position[i]
represents the position of the i-th
chip on a number line. On each move, you can change the position of the i-th
chip by either:
Your goal is to find the minimum cost required to move all the chips to the same position.
position
?
position
array?
The core insight is to recognize that moving chips from even indices to other even indices, or from odd indices to other odd indices, costs 0 (since they can be moved by 2 units). Therefore, the cost only incurs when we move a chip from an even index to an odd index, or vice versa.
#include <vector>
#include <algorithm>
class Solution {
public:
int minCostToMoveChips(std::vector<int>& position) {
int evenCount = 0;
int oddCount = 0;
// Count the number of chips at even and odd positions
for (int pos : position) {
if (pos % 2 == 0) {
++evenCount;
} else {
++oddCount;
}
}
// Return the minimum cost to align all chips
return std::min(evenCount, oddCount);
}
};
The time complexity of this solution is ( O(n) ), where ( n ) is the number of elements in the position
array. This is because we iterate over the array once to count the chips at even and odd positions. The space complexity is ( O(1) ) as we only use a few extra variables to store the counts.
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?