Skip to content

Commit 568fe5f

Browse files
solves fair candy swap
1 parent a7eaedd commit 568fe5f

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@
239239
| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list) | [![Java](assets/java.png)](src/MiddleOfTheLinkedList.java) |
240240
| 883 | [Projection Area of 3D Shapes](https://leetcode.com/problems/projection-area-of-3d-shapes) | [![Java](assets/java.png)](src/ProjectionAreaOf3DShapes.java) |
241241
| 884 | [Uncommon Words from 2 Sentences](https://leetcode.com/problems/uncommon-words-from-two-sentences) | [![Java](assets/java.png)](src/UncommonWordsFromTwoSentences.java) |
242-
| 888 | [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap) | |
242+
| 888 | [Fair Candy Swap](https://leetcode.com/problems/fair-candy-swap) | [![Java](assets/java.png)](src/FairCandySwap.java) |
243243
| 892 | [Surface Area of 3D Shapes](https://leetcode.com/problems/surface-area-of-3d-shapes) | |
244244
| 893 | [Groups of Special Equivalent Strings](https://leetcode.com/problems/groups-of-special-equivalent-strings) | |
245245
| 896 | [Monotonic Array](https://leetcode.com/problems/monotonic-array) | |

src/FairCandySwap.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import java.util.Arrays;
2+
import java.util.HashSet;
3+
import java.util.Set;
4+
5+
public class FairCandySwap {
6+
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
7+
final int difference = Arrays.stream(aliceSizes).sum() - Arrays.stream(bobSizes).sum();
8+
final int required = difference / 2;
9+
Set<Integer> bobCandies = new HashSet<>();
10+
for (int candy : bobSizes) bobCandies.add(candy);
11+
for (int candy : aliceSizes) {
12+
if (bobCandies.contains(candy - required)) return new int[] {candy, candy - required};
13+
}
14+
return new int[] {};
15+
}
16+
}

0 commit comments

Comments
 (0)