Every day a Leetcode
Solution 1: Greedy
First it is easy to derive:
- Changing from an even (odd) position to another even (odd) position, the minimum overhead at this time is 0;
- To change from an even (odd) position to another odd (even) position, the minimum overhead at this time is 1.
Then we can regard the initial "chips" in each even-numbered position as a whole, and the "chips" in each odd-numbered position as a whole. Because our goal is to finally move all the "chips" to the same position, there are only two situations for the final position:
- Moving to an even position, the minimum cost at this time is the number of "chips" in the initial odd position.
- Move to an odd-numbered position, the minimum cost at this time is the number of "chips" in the initial even-numbered position
code:
/*
* @lc app=leetcode.cn id=1217 lang=cpp
*
* [1217] 玩筹码
*/
// @lc code=start
class Solution
{
public:
int minCostToMoveChips(vector<int> &position)
{
int odd = 0, even = 0;
for (int &index : position)
{
if (index % 2)
odd++;
else
even++;
}
return min(odd, even);
}
};
// @lc code=end
result:
Complexity analysis:
Time complexity: O(n), where n is the length of the array position, and only one traversal of the array is performed.
Space complexity: O(1).