Problem
You are given an array of length . There are two empty arrays, and . You have to put every element of into either or .
The score of an array is defined as the square of the sum of all of its elements. Find the minimum possible absolute difference between the score of and .
Input Format:
- The first line of input contains a single integer , denoting the number of test cases.
- The first line of each test case contains a single integer , denoting the length of the array .
- The second line of each test case contains integers, denoting the elements of array .
Output Format:
For each test case, print the minimum possible absolute difference between the score of and the score of .
Constraints:
1 <= N <= 20
1 <= A[i] <= 10⁸
Sample Input | Sample Output |
---|---|
2 | 44 |
4 | 0 |
4 5 10 3 | |
5 | |
1 3 5 4 5 |
First test case:
We can put the third element in and the other elements in .
The score of is .
The score of is .
Their absolute difference is .
It can be shown that this is the minimum possible absolute difference. Thus, the answer is .
Second test case:
We can put the first three elements in and the last two elements in .
The score of is .
The score of is .
Their absolute difference is . Thus, the answer is .
Solution:-
#include <stdio.h>#include <stdlib.h>#include <limits.h>
// Function to return the minimum of two numberslong long min(long long a, long long b) { return (a < b) ? a : b;}
// Recursive function to calculate the minimum absolute difference// between the scores of two groups formed from the array elementslong long minScoreDifference(int n, int currentIndex, int group1Sum, int group2Sum, int arr[]) { // Base case: when all elements are processed if (currentIndex == n) { // Calculate and return the absolute difference of squares of sums return llabs(1LL * group1Sum * group1Sum - 1LL * group2Sum * group2Sum); } else { // Recursive case 1: Include the current element in the first group (group1Sum) long long option1 = minScoreDifference(n, currentIndex + 1, group1Sum + arr[currentIndex], group2Sum, arr); // Recursive case 2: Include the current element in the second group (group2Sum) long long option2 = minScoreDifference(n, currentIndex + 1, group1Sum, group2Sum + arr[currentIndex], arr); // Return the minimum of both options return min(option1, option2); }}
int main() { int testCases; // Number of test cases // Read the number of test cases scanf("%d", &testCases); // Process each test case while (testCases--) { int arrayLength; // Length of the array // Read the length of the array scanf("%d", &arrayLength); int arr[arrayLength]; // Array to store the elements // Read the array elements for (int i = 0; i < arrayLength; i++) { scanf("%d", &arr[i]); } // Calculate the minimum absolute difference between the scores of two groups long long result = minScoreDifference(arrayLength, 0, 0, 0, arr); // Output the result printf("%lld\n", result); } return 0;}
#include <bits/stdc++.h>
using namespace std;
int main() { ios_base::sync_with_stdio(false); // Optimize input/output cin.tie(nullptr);
int testCases; cin >> testCases; // Read the number of test cases
while (testCases--) { int arraySize; cin >> arraySize; // Read the size of the array
vector<int> arr(arraySize); for (int i = 0; i < arraySize; ++i) { cin >> arr[i]; // Read each element of the array }
long long totalSum = accumulate(arr.begin(), arr.end(), 0LL); // Calculate total sum of the array long long minDifference = LLONG_MAX; // Initialize minimum difference
set<long long> subsetSums; // Set to store subset sums int halfSize = arraySize / 2; // Calculate half size of the array
// Generate subset sums for the first half of the array for (int mask = 0; mask < (1 << halfSize); ++mask) { long long currentSubsetSum = 0; for (int i = 0; i < halfSize; ++i) { if (mask & (1 << i)) { currentSubsetSum += arr[i]; // Calculate current subset sum } } subsetSums.insert(currentSubsetSum); // Store the sum in the set }
// Convert set to sorted vector for binary searching vector<long long> sortedSubsetSums(subsetSums.begin(), subsetSums.end());
// Generate subset sums for the second half of the array for (int mask = 0; mask < (1 << (arraySize - halfSize)); ++mask) { long long currentSubsetSum = 0; for (int i = 0; i < (arraySize - halfSize); ++i) { if (mask & (1 << i)) { currentSubsetSum += arr[halfSize + i]; // Calculate current subset sum for second half } }
// Find closest subset sum to minimize the difference auto it = lower_bound(sortedSubsetSums.begin(), sortedSubsetSums.end(), totalSum / 2 - currentSubsetSum); for (auto j = it; j != sortedSubsetSums.end() && j <= it + 1; ++j) { if (j >= sortedSubsetSums.begin() && j < sortedSubsetSums.end()) { // Update minimum difference minDifference = min(minDifference, abs(totalSum * (totalSum - 2 * (currentSubsetSum + *j)))); } } }
cout << minDifference << '\n'; // Output the minimum absolute difference }
return 0; // Successful execution}
Text Copied!
Recommended Post :-
HCL Coding Questions:-
- Swap the adjacent characters of the string
- Double the vowel characters in the string
- Character with their frequency
- Program to find the closest value
- Swap adjacent characters
- Double the vowel characters
- Check valid parenthesis
- Print the characters with their frequencies
- Find closest value
- Word Count
- Program of CaesarCipher
- Program to find the perfect city
- Annual Day | Tech Mahindra coding question
- Find the number of pairs in the array whose sum is equal to a given target.
Full C course:-
Key points:-
- How to set limit in the floating value in python
- What is boolean data type
- How to print any character without using format specifier
- How to check that given number is power of 2 or not
- How to fix limit in double and floating numbers after dot (.) in c++
- How to print a double or floating point number in scientific notation and fixed notation
- How to take input a string in c
- How to reduce the execution time of program in c++.
Cracking the coding interview:-
Array and string:-
Tree and graph:-
Hackerearth Problems:-
- Very Cool numbers | Hacker earth solution
- Vowel Recognition | Hackerearth practice problem solution
- Birthday party | Hacker earth solution
- Most frequent | hacker earth problem solution
- program to find symetric difference of two sets
- cost of balloons | Hacker earth problem solution
- Chacha o chacha | hacker earth problem solution
- jadu and dna | hacker earth solution
- Bricks game | hacker earth problem
- Anti-Palindrome strings | hacker earth solution
- connected components in the graph | hacker earth data structure
- odd one out || hacker earth problem solution
- Minimum addition | Hackerearth Practice problem
- The magical mountain | Hackerearth Practice problem
- The first overtake | Hackerearth Practice problem
- Playing With Characters | Hackerrank practice problem solution
- Sum and Difference of Two Numbers | hackerrank practice problem solution
- Functions in C | hackerrank practice problem solution
- Pointers in C | hackerrank practice problem solution
- Conditional Statements in C | Hackerrank practice problem solution
- For Loop in C | hackerrank practice problem solution
- Sum of Digits of a Five Digit Number | hackerrank practice problem solution
- 1D Arrays in C | hackerrank practice problem solution
- Array Reversal | hackerrank practice problem solution
- Printing Tokens | hackerrank practice problem solution
- Digit Frequency | hackerrank practice problem solution
- Calculate the Nth term | hackerrank practice problem solution
Data structure:-
- Program to find cycle in the graph
- Implementation of singly link list
- Implementation of queue by using link list
- Algorithm of quick sort
- stack by using link list
- program to find preorder post order and inorder of the binary search tree
- Minimum weight of spanning tree
- Preorder, inorder and post order traversal of the tree
MCQs:-
0 Comments