題目

There are some chips, and the i-th chip is at position chips[i].

You can perform any of the two following types of moves any number of times (possibly zero) on any chip:

  • Move the i-th chip by 2 units to the left or to the right with a cost of 0.
  • Move the i-th chip by 1 unit to the left or to the right with a cost of 1.

There can be two or more chips at the same position initially.

Return the minimum cost needed to move all the chips to the same position (any position).

Example 1:

Input: chips = [1,2,3]
Output: 1
Explanation: Second chip will be moved to positon 3 with cost 1. First chip will be moved to position 3 with cost 0. Total cost is 1.

Example 2:

Input: chips = [2,2,2,3,3]
Output: 2
Explanation: Both fourth and fifth chip will be moved to position two with cost 1. Total minimum cost will be 2.

Constraints:

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

題目大意

數軸上放置了一些籌碼,每個籌碼的位置存在數組 chips 當中。你可以對 任何籌碼 執行下面兩種操作之一(不限操作次數,0 次也可以):

  • 將第 i 個籌碼向左或者右移動 2 個單位,代價為 0。
  • 將第 i 個籌碼向左或者右移動 1 個單位,代價為 1。

最開始的時候,同一位置上也可能放着兩個或者更多的籌碼。返回將所有籌碼移動到同一位置(任意位置)上所需要的最小代價。

提示:

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

解題思路

  • 給出一個數組,數組的下標代表的是數軸上的座標點,數組的元素代表的是砝碼大小。砝碼移動規則,左右移動 2 格,沒有代價,左右移動 1 個,代價是 1 。問最終把砝碼都移動到一個格子上,最小代價是多少。
  • 先解讀砝碼移動規則:偶數位置的到偶數位置的沒有代價,奇數到奇數位置的沒有代價。利用這個規則,我們可以把所有的砝碼無代價的摞在一個奇數的位置上和一個偶數的位置上。這樣我們只用關心這兩個位置了。並且這兩個位置可以連續在一起。最後一步即將相鄰的這兩摞砝碼合併到一起。由於左右移動一個代價是 1,所以最小代價的操作是移動最少砝碼的那一邊。奇數位置上砝碼少就移動奇數位置上的,偶數位置上砝碼少就移動偶數位置上的。所以這道題解法變的異常簡單,遍歷一次數組,找到其中有多少個奇數和偶數位置的砝碼,取其中比較少的,就是最終答案。 ��,就是最終答案。

參考代碼

package leetcode

func minCostToMoveChips(chips []int) int {
	odd, even := 0, 0
	for _, c := range chips {
		if c%2 == 0 {
			even++
		} else {
			odd++
		}
	}
	return min(odd, even)
}

func min(a int, b int) int {
	if a > b {
		return b
	}
	return a
}