0% found this document useful (0 votes)
42 views8 pages

Amazon OA

The document outlines a problem where the goal is to maximize the sum of medians from groups of three elements chosen from an array. It suggests sorting the array and forming groups from the largest elements to achieve the highest medians. The provided Java code implements this approach by calculating the total of selected medians based on the sorted array.

Uploaded by

kritikad322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views8 pages

Amazon OA

The document outlines a problem where the goal is to maximize the sum of medians from groups of three elements chosen from an array. It suggests sorting the array and forming groups from the largest elements to achieve the highest medians. The provided Java code implements this approach by calculating the total of selected medians based on the sorted array.

Uploaded by

kritikad322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Understanding :-> Given an array pick some groups of “3” -> your

choice how many groups you have to choose. For each group
calculate the median and that is the answer for that group

-> Problem is asking you to maximize the sum of answers of each


group

-> Observation 0 :- you should always make n/3 groups; because


the more groups you make the larger the final answer will be as all
numbers positive as per greedy algorithm.

-> Observation 1 :- Sort the array for better visualization.

-> sort the array -> For the first group we pick 3 largest elements
of the array -> for the second group we pick 4th 5th 6th largest
elements and so on………. are you sure it will always give the best
answer

-> We want to maximize the median of each group

-> The maximum median possible for first group = second largest
element

Code-
import java.util.*;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size=scanner.nextInt();
int array[]=new int[size + 1];

for (int i=1;i<=size;i++) {


array[i]=scanner.nextInt();
}

Arrays.sort(array);
int group=size/3;
int processed=0;
int total=0;

for (int i=size - 1;i >=1;i-=2) {


total+= array[i];
processed++;
if (processed==group) {
break;
}
}

System.out.println(total);
}
}

You might also like