Skip to content

Commit

Permalink
Alice and Bob candy swap solved
Browse files Browse the repository at this point in the history
  • Loading branch information
sangaryousmane committed Jun 14, 2023
1 parent b8c2c48 commit 34a595d
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/intermediate/Searching.java
Original file line number Diff line number Diff line change
Expand Up @@ -503,10 +503,10 @@ else if (nums[middle] > target)
public static int[] intersectionOfArrays(int[] nums1, int[] nums2) {
Set<Integer> common = new HashSet<>();

Arrays.sort(nums2);
Arrays.sort(nums2); // Sort the second set of elements
for (Integer num : nums1) {
if (isFound(nums2, num))
common.add(num);
if (isFound(nums2, num)) // apply the array u sort to BS
common.add(num); // Add to the set if there's similarity
}
int j = 0;
int[] ans = new int[common.size()];
Expand Down Expand Up @@ -549,4 +549,26 @@ public static int peakMountain(int[] nums) {
}
return start;
}

// https://leetcode.com/problems/fair-candy-swap/description/
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes){
int aliceTotal = 0, bobTotal = 0;

for (int aliceCandy: aliceSizes)
aliceTotal +=aliceCandy;

Set<Integer> bobCandySizes=new HashSet<>();
for (int bobCandy: bobSizes) {
bobTotal += bobCandy;
bobCandySizes.add(bobCandy);
}

int diffOfCandies=(bobTotal - aliceTotal) / 2;
for (int alice: aliceSizes){
if (bobCandySizes.contains(alice+diffOfCandies)){
return new int[]{alice, alice + diffOfCandies};
}
}
return null;
}
}

0 comments on commit 34a595d

Please sign in to comment.