forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Math] Add a solution to Minimum Moves to Equal Array Elements
- Loading branch information
Showing
3 changed files
with
19 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ | ||
* Primary idea: Adding 1 to n - 1 elements is the same as subtracting 1 from one element, | ||
* the best way is to make all the elements equal to the min element. | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(1) | ||
*/ | ||
|
||
class MinimumMovesEqualArrayElements { | ||
func minMoves(_ nums: [Int]) -> Int { | ||
let minNum = nums.min()! | ||
|
||
return nums.reduce(0) { total, num in total + num - minNum } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters