LeetCode1217 play chips (greedy)

topic:

Some chips placed on the number line, the present position of each array chips among the chips.

You can do one of the following two operations on any chips (unlimited number of operations 0 times may be):

The i-th chip to the left or right movement of two units, the cost is zero.
The i-th chip 1 is moved to the left or the right unit, the cost is 1.
The very beginning, the same location may also be placed two or more chips.

Returns the minimum cost to move all the chips on the same position (any position) required.

Example 1:

Input: chips = [1,2,3]
Output: 1
Explanation: the cost of the second chip is moved to position III is 1, the cost of the first chip is moved to position III is 0, 1 of total consideration.
Example 2:

Input: chips = [2,2,2,3,3]
Output: 2
Explanation: fourth and fifth chips moved to two positions are a consideration, the minimum total cost of two.
 

prompt:

1 <= chips.length <= 100
1 <= chips[i] <= 10^9

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/play-with-chips

Ideas:

Greedy: odd positions between the odd-numbered position, can be reached by even steps, i.e. steps 2 steps 2 can be moved past, cost is 0. Even positions and even positions is the same reason, it will move all the different chips even (odd) the position of the minimum cost to the same position is 0, the final result of the movement of only two piles pile located odd positions, pile located even positions. Then after moving in two different positions on the chip is moved to the same position, a movement of a minimum cost, the final answer is at a minimum number of an odd number of positions and even positions on the chip.

Code:

import java.util.*;
import java.math.*;

class Solution {
    public int minCostToMoveChips(int[] chips) {
        int length = chips.length;
        int even = 0, odd = 0;
        for(int i=0; i<length; i++){
            if(chips[i] % 2 == 0) even++;
            if(chips[i] % 2 == 1) odd++;
        }
        return Math.min(even, odd);
    }
}

public class Main {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        Solution solution = new Solution();
        int n = scanner.nextInt();
        int[] chips = new int[n];
        for(int i=0; i<n; i++){
            chips[i] = scanner.nextInt();
        }
        System.out.println(solution.minCostToMoveChips(chips));
    }
}

 

Guess you like

Origin www.cnblogs.com/sykline/p/12233430.html