import java.util.Scanner;
// Brute Force Method
public class DivideLycheeBruteForce {
public static String whoGetsFruits(int n, int[] bunches) {
int totalLychees = 0;
for (int bunch : bunches) {
totalLychees += bunch;
}
if (totalLychees % 2 != 0) {
return "monkey";
}
int targetLychees = totalLychees / 2;
return canDivideEqually(bunches, targetLychees, 0, 0) ? "friends" : "monkey";
}
private static boolean canDivideEqually(int[] bunches, int targetLychees, int index,
int currentSum) {
if (currentSum == targetLychees) {
return true;
}
if (currentSum > targetLychees || index >= bunches.length) {
return false;
}
if (canDivideEqually(bunches, targetLychees, index + 1, currentSum + bunches[index])) {
return true;
}
return canDivideEqually(bunches, targetLychees, index + 1, currentSum);
}
// Optimized Solution: Dynamic Programming
public static String whoGetsFruitsOptimized(int n, int[] bunches) {
int totalLychees = 0;
for (int bunch : bunches) {
totalLychees += bunch;
}
if (totalLychees % 2 != 0) {
return "monkey";
}
int targetLychees = totalLychees / 2;
boolean[] dp = new boolean[targetLychees + 1];
dp[0] = true;
for (int bunch : bunches) {
for (int j = targetLychees; j >= bunch; j--) {
dp[j] = dp[j] || dp[j - bunch];
}
}
if (dp[targetLychees]) {
return "friends";
} else {
return "monkey";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of fruit bunches: ");
int n = scanner.nextInt();
int[] bunches = new int[n];
System.out.println("Enter the number of fruits in each bunch: ");
for (int i = 0; i < n; i++) {
bunches[i] = scanner.nextInt();
}
System.out.println("Using Brute Force Method: " + whoGetsFruitsBruteForce(n, bunches));
System.out.println("Using Optimized Solution: " + whoGetsFruitsOptimized(n, bunches));
scanner.close();
}
}