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];
}
}