Contest link:

https://www.codechef.com/CSPK2020

ANUBTG: Editorial

Author: CodeChef Public Repository

Tester: easy3279

Editorialist : chaitanya_44

Difficulty: Easy

PREREQUISITES:

Tranversing array and sorting array

PROBLEM:

It is winter super sale and all the shops have various offers. Suraj selected N items to buy and he is standing in the billing queue. It was then he noticed the offer “Buy two, get two”. That means for every two items you buy, they give you two items for free. However, items can be of varying price, they always charge for 2 most costly items and give other 2 as free. For example, if the items cost 1, 1, 2, 2, then you have to pay 4 and take all 4 items.

Suraj is busy reordering his items to reduce the total price he has to pay. He can separate the items and get them on different bills if needed. Can you tell me what is the least price Suraj has to pay to buy all the N items?

INPUT:

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. First line of each test case has single integer N. Second line of each test case has N space separated integers, which are the costs of items Suraj want to buy.

CONSTRAINS:

1 ≤ T ≤ 1000

1 ≤ N ≤ 1000

1 ≤ Cost of items ≤ 1000

SOLUTION:

CPP 14:

#include

using namespace std;

#include<bits/stdc++.h>

int main() {

// your code goes here

int t;

cin>>t;

while(t–){

int n;

cin>>n;

int arr[n];

for(int i=0;i<n;i++){

cin>>arr[i];

}

int sum=0;

sort(arr,arr+n);

if(n<4){

cout<<arr[n-1]+arr[n-2]<<endl;

}

else{

int i=n-1;

while(i>=0)

{

if(i>=0)

sum+=arr[i];

if(i-1>=0)

sum+=arr[i-1];

i-=4;

}

}

cout<<sum<<endl;

}

return 0;

}

PYTHON 3.5:

t=int(input())

for _ in range(t):

n=int(input())

l=list(map(int,input().split()))

l.sort()

l=l[::-1]

s=0

c=-1

for i in range(len(l)):

if i%2==0:

c*=-1

if c==1:

s+=l[i]

else:

pass

print(s)