Leetcode1217. Play chips

Every day a Leetcode

Source of topic:

Solution 1: Greedy

First it is easy to derive:

  1. Changing from an even (odd) position to another even (odd) position, the minimum overhead at this time is 0;
  2. 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:

  1. Moving to an even position, the minimum cost at this time is the number of "chips" in the initial odd position.
  2. 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:

insert image description here

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).

Guess you like

Origin blog.csdn.net/ProgramNovice/article/details/131568114