Suraj goes shopping Codechef Solution|Problem Code: ANUBTG

Suraj goes shopping Codechef Solution

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.

Output

For each test case, output a single line containing the required answer.

Constraints

  • 1 ≤ T ≤ 1000
  • 1 ≤ N ≤ 1000
  • 1 ≤ Cost of items ≤ 1000

Example

Sample Input 1 

3
4
1 1 2 2
2
10 200
7
1 1 10 2 2 2 1

Sample Output 1 

4
210
14

Suraj goes shopping- CodeChef Solution in JAVA

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for (int tc = 0; tc < T; tc++) {
			int N = sc.nextInt();
			int[] prices = new int[N];
			for (int i = 0; i < prices.length; i++) {
				prices[i] = sc.nextInt();
			}
			System.out.println(solve(prices));
		}
		sc.close();
	}
	static int solve(int[] prices) {
		List<Integer> sortedPrices = Arrays.stream(prices).boxed().sorted(Collections.reverseOrder())
				.collect(Collectors.toList());
		return IntStream.range(0, sortedPrices.size()).filter(i -> i % 4 <= 1).map(i -> sortedPrices.get(i)).sum();
	}
}

Disclaimer: The above Problem (Suraj goes shopping) is generated by CodeChef but the solution is provided by  Chase2learn.This tutorial is only for Educational and Learning purpose.

Leave a Comment