Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies in the jth box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
Return a n integer arrayanswerwhereanswer[0]is the number of candies in the box that Alice must exchange, andanswer[1]is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
classSolution {
public: vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
int sumA = accumulate(A.begin(), A.end(), 0);
int sumB = accumulate(B.begin(), B.end(), 0);
int delta = (sumA - sumB) /2;
unordered_set<int> setB(B.begin(), B.end());
for (int a : A) {
int b = a - delta;
if (setB.count(b)) return {a, b};
}
return {};
}
};
classSolution {
publicint[]fairCandySwap(int[] A, int[] B) {
int sumA = 0, sumB = 0;
for (int a : A) sumA += a;
for (int b : B) sumB += b;
int delta = (sumA - sumB) / 2;
Set<Integer> setB =new HashSet<>();
for (int b : B) setB.add(b);
for (int a : A) {
int b = a - delta;
if (setB.contains(b)) returnnewint[]{a, b};
}
returnnewint[0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funfairCandySwap(A: IntArray, B: IntArray): IntArray {
val sumA = A.sum()
val sumB = B.sum()
val delta = (sumA - sumB) / 2val setB = B.toSet()
for (a in A) {
val b = a - delta
if (b in setB) return intArrayOf(a, b)
}
return intArrayOf()
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
deffairCandySwap(self, aliceSizes: list[int], bobSizes: list[int]) -> list[int]:
sumA = sum(aliceSizes)
sumB = sum(bobSizes)
delta = (sumA - sumB) //2 setB = set(bobSizes)
for a in aliceSizes:
b = a - delta
if b in setB:
return [a, b]
return []
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnfair_candy_swap(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let sum_a: i32= a.iter().sum();
let sum_b: i32= b.iter().sum();
let delta = (sum_a - sum_b) /2;
let set_b: std::collections::HashSet<_>= b.iter().cloned().collect();
for&x in&a {
let y = x - delta;
if set_b.contains(&y) {
returnvec![x, y];
}
}
vec![]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
fairCandySwap(A: number[], B: number[]):number[] {
constsumA=A.reduce((a, b) =>a+b, 0);
constsumB=B.reduce((a, b) =>a+b, 0);
constdelta= (sumA-sumB) /2;
constsetB=newSet(B);
for (constaofA) {
constb=a-delta;
if (setB.has(b)) return [a, b];
}
return [];
}
}
⏰ Time complexity: O(n + m), where n and m are the lengths of aliceSizes and bobSizes. We compute sums and build a set in linear time, and then do a single pass.
🧺 Space complexity: O(m), for storing Bob’s box sizes in a set.