Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- /*
- given an N positive integers , task is to find max median sum , you can find median from any random group of 3 elements from the
- array , you cant reuse the same elements ,once you used in group , you can form any number of 3 element groups from array
- */
- /**
- important point to understand here -
- you can form max n/3 groups from array,lets use all of them as all are positive numbers and task is to maximise
- lets assume some nums exist in sorted order
- a b c d x y z
- z can never be median nor can be reused , so focus on y's in the group
- think how you can maximise the y's in the median group
- in a sorted array as above
- you can form a y z instead of x y z
- you can form b d x instead of b c d
- so for left side elements you are taking min elements to cover left part, which helps you to be your medians as max as possible
- */
- /*
- //inputs for array , given you positive integer array
- 7 8 9 4 5 6 10 1 2 3
- expected output -
- The result is 21
- */
- @SuppressWarnings("unused")
- public class A20250107_maxMedianSum {
- static Scanner sc = new Scanner(System.in);
- private static int[] getArray() {
- String[] sArr = sc.nextLine().split(" ");
- int[] arr = Arrays.stream(sArr).mapToInt(Integer::parseInt).toArray();
- return arr;
- }
- private static char[] getCharArray() {
- String[] sArr = sc.nextLine().split(" ");
- char[] cArr = new char[sArr.length];
- for (int i = 0; i < sArr.length; i++) {
- cArr[i] = sArr[i].charAt(0); // Take the first character of each string
- }
- return cArr;
- }
- private static int getMax(int[] arr) {
- int currMax = Integer.MIN_VALUE;
- for (int curr : arr) {
- currMax = Math.max(currMax, curr);
- }
- return currMax;
- }
- public static void main(String args[]) {
- // prepare the inputs
- int[] arr = getArray();
- int arrLen = arr.length;
- int lastIndex = arrLen - 1;
- Arrays.sort(arr);
- int possibleGroupsCount = (int) Math.floor(arrLen/3);
- int sum=0;
- for(int j=lastIndex-1;j>=0;j-=2){
- sum+=arr[j];
- possibleGroupsCount--;
- if(possibleGroupsCount<=0){
- break;
- }
- }
- int res = sum;
- System.out.println("The result is " + res);
- }
- }
- class Pair{
- int row;
- int col;
- public Pair(int i,int j){
- this.row = i;
- this.col = j;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement