462 Minimum Moves to Equal array Elements II minimum number of moves make the elements equal II

Source: Internet
Author: User

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, with each move adding 1 or minus 1 to the selected element. You can assume that the array has a maximum length of 10000.
For example:
Input:
[A]
Output:
2
Description
Only two actions are necessary (remember that each step can only add 1 or minus 1 to one of the elements):
[2,2,3] = [2,2,2]
See: https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/

C++:

Class Solution {public:    int minMoves2 (vector<int>& nums) {        int res = 0, i = 0, j = nums.size ()-1;        Sort (Nums.begin (), Nums.end ());        while (I < j)        {            res + = nums[j--]-nums[i++];        }        return res;    }};

Reference: https://www.cnblogs.com/grandyang/p/6089060.html

462 Minimum Moves to Equal array Elements II minimum number of moves make the elements equal II

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.