简体   繁体   English

用Java打印最大值和最小值

[英]Print Max and Min Value in Java

I have just started practicing on HackerRank to improve my coding skills. 我刚开始练习HackerRank以提高我的编码技能。 I'm mostly using Java as my preferred language. 我主要使用Java作为我的首选语言。 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. 我已经清除了15个测试用例中的5个 ,但仍有10个案例需要完成。 Those who are on the hackerrank can see the question by following this link : Min-Max Sum 那些在黑客上的人可以通过以下链接看到这个问题: 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] . 例如, 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 . 我们的最小总和是1+3+5+7=16 ,我们的最大总和是3+5+7+9=24 We would print 16 24 我们打印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.) (输出可以大于32位整数。)

Sample Input 1 2 3 4 5 样本输入 1 2 3 4 5

Sample Output 10 14 样本输出 10 14

Explanation 说明

Our initial numbers are 1, 2, 3, 4, and 5 . 我们的初始数字是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. 我们也可以通过迭代num array ,找到最大值和最小值来做到这一点。

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. 请注意: arr中的元素数量是固定的,仅为5。

I have got to know that amongst the 10 fails, I got to know about one test case, which is like this : 我必须知道在10个失败中,我了解了一个测试用例,它是这样的:

Input(stdin) 256741038 623958417 467905213 714532089 938071625 输入(stdin) 256741038 623958417 467905213 714532089 938071625

Expected Output 2063136757 2744467344 预期产出 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. 你有正确的想法(尽管排序数组有点过分,因为你只需要它的最大值和最小值),但是当你对这些大整数求和时,你会溢出 sumtot变量并得到错误的答案。 Using long s instead should solve the issue: 使用long s代替应该解决问题:

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: 注意,顺便说一句,使用Java 8的流你可以实现相同的逻辑并保存很多样板代码,以及O(nlog(n))排序:

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. 首先,您需要使用long,因为值的总和可以推断整数最大值。 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. 请参阅此解决方案,该解决方案为2N解决方案执

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) 排序有助于将时间复杂度从O(n * n)减少到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... 完全相同的逻辑适用于minimumSum ...

Thinking this way reduce the effort and time to solve the problem. 以这种方式思考减少了解决问题的努力和时间。

For example - in one loop find the maximumElement and minimumElement. 例如 - 在一个循环中找到maximumElement和minimumElement。

In second loop sum the both results - sumMax += array[index] avoiding the index of maximumElement; 在第二个循环中求和两个结果 - sumMax += array[index]避免maximumElement的索引; sumMin += array[index] avoiding the index of minimumElement. sumMin += array[index]避免使用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. 步骤1我们将在数组中找到最小元素。

Step-2 we will find the maximum element in the array. 在步骤2中,我们将找到数组中的最大元素。

step-3 we are going to calculate the sum of all the elements in the array. 在步骤3中,我们将计算数组中所有元素的总和。

Step-4 we are calculating the minsum by subtracting max value from total sum in the array. 步骤4我们通过从数组中的总和中减去最大值来计算minsum。

Step-5 we are calculating the maxsum by subtracting min value from the overall sum. 步骤5我们通过从总和中减去最小值来计算最大值。

And finally, we are going to print minsum and maxsum. 最后,我们将打印minsum和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 . 我希望它会有所帮助。但是你还需要更多的解释,然后你可以参考这个教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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