java min value_Print Max and Min Value in Java

本文作者分享了在 HackerRank 上练习编程技能的经历,具体讨论了一个涉及找出5个正整数中任意4个求和得到的最小和最大值的问题。作者的算法实现了对所有可能的组合进行遍历,但未能通过所有测试用例。问题关键在于找到计算最小和最大值的更高效方法。已知有一个测试用例输入为 [2, 5, 6, 7, 41],预期输出为 [20, 41]。作者的算法需要进一步优化以解决所有情况。
摘要由CSDN通过智能技术生成

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

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

for(int j=1;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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值