🔗 🟢 3736. Minimum Moves to Equal Array Elements III

Problem Statement

題目簡述

給定一個整數陣列 nums\textit{nums}。每次操作可以選擇任意一個元素 nums[i]\textit{nums}[i] 並將其值加 11。
請回傳使陣列中所有元素都相等所需的最少總操作次數。

Constraints

約束條件

  • 1≤nums.length≤1001 \le \textit{nums.length} \le 100
  • 1≤nums[i]≤1001 \le \textit{nums}[i] \le 100

思路:貪心對齊最大值

每次操作只能將單一元素加 11 而無法減少,因此最終所有元素相等的目標值必然不小於陣列的最大值 mx=max⁡(nums)\textit{mx} = \max(\textit{nums})。

依 貪心(Greedy) 原則,目標值每多增加 11,全部 nn 個元素都必須多操作 11 次;因此直接取 mx\textit{mx} 作為最終相等的目標值即為最優。此時每個元素 xx 需要補齊 mx−x\textit{mx} - x 次,利用 數學(Math) 加總所有差值即得最少總操作次數:

∑x∈nums(mx−x)\sum_{x \in \textit{nums}} (\textit{mx} - x)

複雜度分析

  • 時間複雜度:O(n)\mathcal{O}(n),其中 nn 為 nums\textit{nums} 的長度。求最大值與計算差值總和各遍歷陣列一次。
  • 空間複雜度:O(1)\mathcal{O}(1),僅使用常數額外空間。

Code

1
2
3
4
class Solution:
def minMoves(self, nums: List[int]) -> int:
mx = max(nums)
return sum(mx - x for x in nums)

寫在最後

Cover Image Credit

The cover image was created by @Shacola. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.