greedy implementation sortings *900

Please click on ads to support us..

Python Code:

n = int(input())
arr = list(map(int, input().split()))
arr.sort(reverse=True)
a = list(filter(lambda x: x % 2, arr))
b = list(filter(lambda x: not x % 2, arr))
s = sum(arr)
k = min(len(a), len(b))
for i in range(k):
    s -= a[i] + b[i]
if len(a) > len(b):
    s -= a[k]
elif len(b) > len(a):
    s -= b[k]
print(s)

C++ Code:

#include<bits/stdc++.h>

#define ll long long

#define ld long double

#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)



using namespace std;



int main ()

{

	fast;

	

	vector<int> v1;

	vector<int> v2;

	

	int n;

	cin>>n;

	int a;

	

	while ( n-- )

	{

		cin>>a;

		if ( a % 2 == 0 )

		{

			v1.push_back(a);

		}

		else {

			v2.push_back(a);

		}

	}

	int x = v1.size();

	int y = v2.size();

	

	if ( abs ( x - y ) <= 1 )

	{

		cout<<0<<endl;

		return 0;

	}

	else {

	sort ( v1.begin(), v1.end() );

	sort ( v2.begin(), v2.end() ); 

	int s = 0;

	if ( x > y )

	{

		for ( int i = 0; i < abs ( x - y ) - 1; i++ )

		{

			s += v1[i];

		}

	}

	else

	{

		for ( int j = 0; j < abs ( x - y ) - 1; j++ )

		{

			s += v2[j];

		}

	}

	cout<<s<<endl;

	}

	return 0;

}


Comments

Submit
0 Comments
More Questions

Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game
Char Sum
Two Strings
Anagrams
Prime Number
Lexical Sorting Reloaded
1514A - Perfectly Imperfect Array
580A- Kefa and First Steps
1472B- Fair Division
996A - Hit the Lottery
MSNSADM1 Football
MATCHES Playing with Matches
HRDSEQ Hard Sequence
DRCHEF Doctor Chef
559. Maximum Depth of N-ary Tree