I am trying out the following approach:
1.I sort the array of weights in decreasing order and "put" the largest weight in one group.
2.Then I keep adding weights to the other group until it becomes larger.
3.Then I start adding apples to the first group until this is one is larger and again start putting apples in the other group and keep on going like this until i reach the end of the array.
4.And then I print the difference between the total weights of the two groups.
My solution gives the correct answer with the sample test cases and a few others too but I am getting a WA, so can anyone suggest something I can do to correct my code. Code:
#include <bits/stdc++.h>
using namespace std;
#define B begin()
#define E end()
#define I iterator
using pii = pair < int , int >;
using vi = vector < int >;
using llu = unsigned long long int;
using ll = long long int;
//ofstream cout ("op.txt");
//ifstream fin("inp.in");
int main ()
{
ll n;
cin >> n;
vector <ll> vec(n);
ll val;
for ( int i = 0 ; i < n ; i ++ ){
cin >> val;
vec[i] = val;
}
sort ( vec.B , vec.E , greater<ll>() );
ll ansa = 0 , ansb = 0 ;
ansa = vec[0];
for ( int i = 1; i < n ; i++ ){
if ( ansb < ansa )
ansb += vec[i];
else
ansa += vec[i];
}
cout << max( ansa , ansb ) - min( ansa , ansb );
return 0;
}
Any and all help is appreciated