Learn Go Programming - Day 3 - Minimum Moves to Equal Array Elements II

in #programming5 years ago
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment or decrement an element of the array by 1.

Example 1:

Input: nums = [1,2,3]
Output: 2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]
Example 2:

Input: nums = [1,10,2,9]
Output: 16

There is no while keyword in go.

func minMoves2(nums []int) int {
    var l = 0
    var r = len(nums) - 1
    var sum = 0
    sort.Ints(nums)
    for l < r {
        sum += nums[r] - nums[l]
        l ++;
        r --;
    }
    return sum;
}

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

  1. Voting Algorithm Updated to Favor those High Delegations!
  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

如何创建?不是很懂,请大佬指教。😊😊

[WhereIn Android] (http://www.wherein.io)

hi brother . you know brother 😉

[WhereIn Android] (http://www.wherein.io)

Hy @Justyy I knew about you today, and my witness vote surely for you... 🙂
You are doing extra ordinary great work.. more power to you !

Thank yoU!

You are welcome !

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60159.19
ETH 1576.47
USDT 1.00
SBD 0.42