To solve this problem, we'll use the greedy approach to partition the battle powers into two teams such that the difference in their total battle powers is minimized.
Here's the step-by-step process:
-
Read Input: Read the number of participants n and their battle powers a_i.
-
Sort Battle Powers: Sort the battle powers in decreasing order. This ensures we distribute the largest battle powers first, which helps in balancing the two teams.
-
Initialize Sums: Initialize two sums sum1 and sum2 to represent the total battle power of each team.
-
Distribute Battle Powers:
- Iterate through the sorted battle powers.
- At each step, assign the current battle power to the team with the lesser total battle power.
- Update the respective team's total battle power.
-
Calculate Difference: After distributing all battle powers, calculate the absolute difference between sum1 and sum2. This is the minimal absolute difference in total battle power between the two teams.
-
Output: Print the minimal absolute difference.
Here's the Java code implementing the above steps:
import java.util.*;
public class BattlePowerDifference {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the number of participants
int n = scanner.nextInt();
int[] battlePowers = new int[n];
int totalSum = 0;
// Read the battle powers
for (int i = 0; i < n; i++) {
battlePowers[i] = scanner.nextInt();
totalSum += battlePowers[i];
}
// Sort the battle powers in decreasing order
Arrays.sort(battlePowers);
// Reverse the array to get decreasing order
for (int i = 0; i < n / 2; i++) {
int temp = battlePowers[i];
battlePowers[i] = battlePowers[n - i - 1];
battlePowers[n - i - 1] = temp;
}
// Initialize team sums
int sum1 = 0;
int sum2 = 0;
// Distribute battle powers to minimize difference
for (int i = 0; i < n; i++) {
if (sum1 <= sum2) {
sum1 += battlePowers[i];
} else {
sum2 += battlePowers[i];
}
}
// Compute the minimal absolute difference
int difference = Math.abs(sum1 - sum2);
// Output the result
System.out.println(difference);
}
}
Explanation:
- We use a
Scanner to read inputs from the console.
- The battle powers are stored in an array
battlePowers.
- We sort this array in decreasing order to prioritize distributing larger battle powers first.
- We then use a simple greedy method to assign each participant to the team with the current lesser total battle power.
- Finally, we compute and print the minimal absolute difference between the two teams' total battle powers.
Sample Input:
4
7 4 5 3
Sample Output:
1
This code will produce the expected output for the provided sample and should perform efficiently for larger inputs as well.