Leetcode 1217. Minimum Cost to Move Chips to The Same Position
We have n
chips, where the position of the i-th
chip is position[i]
. We need to move all chips to the same position. In one step, we can:
x
to x + 2
or x - 2
).x
to x + 1
or x - 1
).Given an array position
, return the minimum cost needed to move all the chips to the same position.
Range of n
: How large can n
be?
Answer: The maximum length of the array position
can be up to 100
.
Range of positions: Are the positions large? Answer: No constraints are specified, so positions can be any integers.
Output Expectations: Should the output be the minimum cost as an integer? Answer: Yes, the output should be a single integer representing the minimum cost.
public class Solution {
public int minCostToMoveChips(int[] position) {
int evenCount = 0;
int oddCount = 0;
for (int pos : position) {
if (pos % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
return Math.min(evenCount, oddCount);
}
}
O(n)
, where n
is the number of elements in the position
array. We are iterating through the array once.O(1)
, since we are only using a constant amount of additional space to store the counts of even and odd positions.This approach ensures that we efficiently calculate the minimum cost required to move all chips to the same position.
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?