简体   繁体   中英

Print Max and Min Value in Java

I have just started practicing on HackerRank to improve my coding skills. I'm mostly using Java as my preferred language. I have got this question, and I have tried my level best to give the solution but didn't clear all the test cases. I have cleared 5 out 15 test cases , but still 10 cases are left to be done. Those who are on the hackerrank can see the question by following this link : Min-Max Sum

I'm anyway giving the brief description of the question :

PROBLEM STATEMENT

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

For example, arr=[1,3,5,7,9] . Our minimum sum is 1+3+5+7=16 and our maximum sum is 3+5+7+9=24 . We would print 16 24

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)

Sample Input 1 2 3 4 5

Sample Output 10 14

Explanation

Our initial numbers are 1, 2, 3, 4, and 5 . We can calculate the following sums using four of the five integers:

If we sum everything except 1, our sum is 2+3+4+5=14.
If we sum everything except 2, our sum is 1+3+4+5=13.
If we sum everything except 3, our sum is 1+2+4+5=12.
If we sum everything except 4, our sum is 1+2+3+5=11.
If we sum everything except 5, our sum is 1+2+3+4=10.

My Algo

  for(i=0; i<arr.length; i++){
    totSum += arr[i];
  }

  sumOne = totSum - arr[0];
  sumTwo = totSum - arr[1];
  sumThree = totSum - arr[2];
  sumFour = totSum - arr[3];
  sumFive = totSum - arr[4];

  int[] num = {sumOne, sumTwo, sumThree, sumFour, sumFive};
  int temp = 0;
  for(i=0;i<num.length;i++){
    for(int j=1;j<(num.length-i);j++){
        if(num[j-1] > num[j]){  
            //swap elements  
            temp = num[j-1];  
            num[j-1] = num[j];  
            num[j] = temp;  
        }
    }
  }

  System.out.print(num[0] + " " + num[4]);

We can also do that by iterating through the num array , and finding the max and min value.

But somehow after all doing this, I don't clear this module.

Please Note : The number of elements in arr is fixed that is 5 only.

I have got to know that amongst the 10 fails, I got to know about one test case, which is like this :

Input(stdin) 256741038 623958417 467905213 714532089 938071625

Expected Output 2063136757 2744467344

You have the right idea (although sorting the array is a bit of an overkill, since you just need its maximum and minimum values), but when you sum these large integers, you overflow the sumtot variable and get a wrong answer. Using long s instead should solve the issue:

long totSum = 0;
for(int i=0; i<arr.length; i++){
    totSum += arr[i];
}

long sumOne = totSum - arr[0];
long sumTwo = totSum - arr[1];
long sumThree = totSum - arr[2];
long sumFour = totSum - arr[3];
long sumFive = totSum - arr[4];

long[] num = {sumOne, sumTwo, sumThree, sumFour, sumFive};
long temp = 0;
for(int i=0;i<num.length;i++){
    for(int j=1;j<(num.length-i);j++){
        if(num[j-1] > num[j]){
            //swap elements
            temp = num[j-1];
            num[j-1] = num[j];
            num[j] = temp;
        }
    }
}

System.out.print(num[0] + " " + num[4]);

Note, BTW, that using Java 8's streams you can implement the same logic and save a lot of the boilerplate code, as well of the O(nlog(n)) sorting:

IntSummaryStatistics stats = Arrays.stream(arr).summaryStatistics();

System.out.println
    ((stats.getSum() - stats.getMax()) + " " + (stats.getSum() - stats.getMin()));

First of all, you need to use long, as the sum of values can extrapolate the integer max value. Then, you don't need the double loop and you're probably failing some performance test cases due to that. See this solution which does 2 separated loops for a 2N solution.

package minmaxsum;

public class MinMaxSum {
  public static void main(String[] args) {
    MinMaxSum mms = new MinMaxSum();
    mms.printMinMaxSum(new int[] {256741038, 623958417, 467905213, 714532089, 938071625});

    // mms.printMinMaxSum(new int[] {1, 3, 5, 7, 9});
  }

  public void printMinMaxSum(int[] arr) {
    long totalSum = 0;
    for (int num : arr) {
      totalSum += num;
    }

    long min = Long.MAX_VALUE;
    long max = Long.MIN_VALUE;

    for (int num : arr) {
      long currentSum = totalSum - num;

      min = Math.min(min, currentSum);
      max = Math.max(max, currentSum);
    }

    System.out.println(min + " " + max);
  }
}

This works for all test cases. Just submitted the code

 static void miniMaxSum(int[] arr) {
         Arrays.sort(arr);
            long minSum=0,maxSum=0;
            for(int i=0;i<4;i++){
               minSum+=arr[i];
               maxSum+=arr[arr.length-1-i] ;
            }
            System.out.println(minSum + " " + maxSum);

    }

Not all test cases have sorted data. Once array is sorted single loop is enough to calculate min and max sum. Sorting helped to reduce time complexity from O(n*n) to O(nlogn)

There is a need to change the way of thinking: as a programmer usually is better to think like the machine than a human.

Ask yourself, what would be the maximumSum of an array without one element? And the answer is the sum of all elements except the maximum value element. So, if you simply find the element with the maximum value, and sum the rest elements it's the first part of the solution. Exactly the same logic is applicable to minimumSum...

Thinking this way reduce the effort and time to solve the problem.

For example - in one loop find the maximumElement and minimumElement.

In second loop sum the both results - sumMax += array[index] avoiding the index of maximumElement; sumMin += array[index] avoiding the index of minimumElement.

Of course everything of above can be done in just one loop, but since this is your task to improve your programming skills, I'll leave it to you (as well as writing the code).

Here is the algorithm to solve this problem.

Algorithm-

Step-1 we are going to find a minimum element in the array.

Step-2 we will find the maximum element in the array.

step-3 we are going to calculate the sum of all the elements in the array.

Step-4 we are calculating the minsum by subtracting max value from total sum in the array.

Step-5 we are calculating the maxsum by subtracting min value from the overall sum.

And finally, we are going to print minsum and maxsum.

and here is the implementation of this algorithm.

static void miniMaxSum(int[] arr) {
        long min = 0, max = 0, sum = 0;
        min = arr[0];
        max = min;
        sum = min;
        for (int i = 1; i < arr.length; i++) {
            sum += arr[i];
            if (arr[i] < min) {
                min = arr[i];
            }
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        System.out.print((sum - max) + " " + (sum - min));

    }

I hope it will help.but still you need more explanation then you can refer this tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM