There are two arrays a and B whose sizes are n. By exchanging elements in a and B, sum (a)-sum (B) is minimized ., Sum-sum

Source: Internet
Author: User

There are two arrays a and B whose sizes are n. By exchanging elements in a and B, sum (a)-sum (B) is minimized ., Sum-sum

Today, when I browsed the web page, I found a link called Huawei interview questions (code written in 8 minutes). I'm not sure about the authenticity. It's just curious. Let's go and have a look.

This may be a very old question, because I saw a lot of comments under this question. I mentioned XX sorting, memory usage, and other words.

A clown is a newbie and wants to solve his questions in his own way. It is a coincidence that there are similarities.

Solution:

(1) Some predecessors used sorting in solving the problem, but I don't think it is necessary. The sum (a)-sum (B) after sorting is different from the sam (a) in any messy order) -The results of sam (B) must be consistent;

(2) If c [I] = a [I]-B [I], sum is the addition of array c []; after a [I] is exchanged with B [I, c [I] = B [I]-a [I], sum_new is the addition of the new array c;

(3) sum-sum_new = a [I]-B [I]-(B [I]-a [I]) = 2 * (a [I]-B [I]) = 2 * c [I], sum_new = sum-2 * c [I];

CODE:

Int sum = 0;

Int sum_new = 0;

Int I = n;

Int c [n] = {0 };


While (I --){

A [I]-B [I] = c [I];

Sum + = c [I];

}

While (n --){

Sum_new = sum-2 * c [n];

If (sum_new * sum_new <sum * sum) {// the absolute value decreases, indicating that the exchange is correct

A [n] ^ = B [n];

B [n] ^ = a [n];

A [n] ^ = B [n];

}
}

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.