- Practice
- Algorithms
- Warmup
- Mini-Max Sum
- Discussions

# Mini-Max Sum

# Mini-Max Sum

olivierliu + 27 comments This is my code in Python. Should be easy to understand even for beginners.

lst = map(int,raw_input().strip().split(' ')) x = sum(lst) print (x-(max(lst))), (x-(min(lst)))

jmend + 3 comments The only bad thing about this is that it required two iterations. It's nice and concise though.

Enether + 3 comments It actually iterates through the list 4 times in total.

`map`

,`sum`

,`max`

and`min`

all iterate once through the list.JustGosu + 2 comments It doesn't matter that much, as you do fewer operations every iteration. There's only minor difference between doing something 1 time in 4 iterations and doing it 4 times in 1 iteration, and clearly input size of 5 is not the case where we should care that much ;)

tarsum + 1 comment I'd say it does, at least for larger number of integers(think about real world). If you have to go trough list 4 times and I have to do it 2 times your program will take twice as much, in worse case scenario.

I think that should be a good part of learning, to make thinks go faster. And not to say my solution is any faster.

rzhang117 + 1 comment Those kinds of differences aren't as big (and therefore as consequential) as exponential or logarithmic, which is what programmers use to define time complexity. Therefore, we don't care if the time it takes is 4 times the length of the list or 2 times the length of the list, but rather if it is O(n^2) or (e^n), where n is the length of the list. And even if the time complexity is O(b*(n^2)) or O(c*(n^2)), where b and c are constants, we don't care, we simply put it as O(n^2). We care more about that than comparing your "best case" scenario to his "worse case" scenario.

andrewsenner + 2 comments Remove the constant! Should focus on rate-of-growth rather than constant speed operations. :) O(n) = O(2n) = O(3n) etc.. When factoring time complexities of algorithms into your function.

Like rzhang said: How fast does the time it take to complete the operation grow relative to the number of entries in the dataset.

If you have something that grows at a rate of O(n^2) (e.g. nested for loop) you have to analyze every element for every element of an array. (Google bubble sort: worst-case is O(n^2), and we only care about worst-case in most situations)

If you have something that grows at a rate of O(log n) (e.g. Binary Search Tree, B-Tree, Red-Black Tree, etc. I know, I'm getting a little bit into data structures in the algorithms section.) you have the ability to reach what you're looking for, add what you're adding, remove what you're removing without having to look at every single element. (Google heap sort: worst-case is O(n log n))

You should also consider the space complexity (how much memory) of your algorithm. Bubble sort may have a worst-case time complexity of O(n^2), but it's space complexity is O(1), which is the best you can get. Radix sort has a worst-case time complexity of O(nk), but it's space complexity is higher at O(n+k).

gouripanda4 + 0 comments thankes:)

bkgonzales157 + 1 comment Yeah, but most algorithms for this problem would be Θ(n), in which case the constant would matter because we're aiming for marginal speed ups.

chuckwondo + 0 comments Yes, and don't be fooled by thinking that an algorithm that iterates only once over the items is necessarily faster than one that iterates over them multiple times.

The number of operations per iteration plays an important role, so an algorithm that iterates once, but with many operations, can be slower than an algorithm that iterates multiple times with very few operations per iteration, because the latter algorithm may perform fewer total operations.

As a case in point, here is a close Kotlin equivalent of the Python code at the top of this thread:

fun miniMaxSum(arr: Array<Long>): Unit = arr.sum().let { println("${it - arr.max()!!} ${it - arr.min()!!}") }

The code above iterates over the array 3 times: once each for

`sum`

,`max`

, and`min`

.Here's another solution that iterates over the array only once, collecting the running sum, min, and max simultaneously along the way. Yes, you might argue it's a bit contrived, but it's not a totally unreasonable solution, at it proves my point.

fun miniMaxSum(arr: Array<Long>): Unit = arr.fold(listOf(0, Long.MAX_VALUE, Long.MIN_VALUE)) { (sum, min, max), e -> listOf(sum + e, Math.min(min, e), Math.max(max, e)) }.let { (sum, min, max) -> println("${sum - max} ${sum - min}") }

The overhead of this approach (1 iteration) causes it to take nearly 10 times longer than the preceding solution (3 iterations). Of course, the timings I took were very rough, and if the array were longer, the overhead of the latter solution might be less significant, but in any case, the latter solution (1 iteration) is clearly and significantly less performant than the former solution (3 iterations).

Here is another solution that iterates over the array only once, but is indeed faster than the first solution (3 iterations) above, by approximately 50% for 5 items (YMMV):

fun miniMaxSumLoop(arr: Array<Long>) { var sum = 0L var min = Long.MAX_VALUE var max = Long.MIN_VALUE for (e in arr) { sum += e if (e < min) min = e else if (e > max) max = e } println("${sum - max} ${sum - min}") }

The code is longer than the first solution, and is arguably less readable. It certainly (arguably?) imposes a bit more cognitive load to comprehend than the first solution does. In this case, it could be argued that the first solution is more desirable. In other words, at some point, the difference in performance might not be large enough to give up the arguably clearer solution. Ease of understanding might simply trump performance.

There's one more thing to consider here as well. Because of the simplicity (and clarity) of the first solution, the likelihood of bugs is greatly reduced due to the use of built-in functionality that precludes the need for explicit looping, as given in the third solution. When you use implicit looping, you introduce the chance for one-off bugs, and the like.

S11170031062 + 0 comments yes

engnr_plusplus + 0 comments constants don't change the big O

ichidan + 1 comment Yes I think that's why I believe a C/C++ solution iterating through the values once, performing summing, min'ing, and max'ing should be a lot faster. Although I wonder if python or any other language can intelligently identify that sum(a), max(a), min(a) are all performed on the same constant data and therefore compute them prior to their calls. I may be overestimating the power of such compilers/interpreters.

jie_lyu + 0 comments we can write a loop in python and identify sum, max and min in one iteration

yashwanth12 + 1 comment this can be done in a single iteration i think you can find the sum while scanning the inputs and now run a loop from 0 to n-1 and substract an element from sum and update min and max variables after updating again add that element to sum.... if any wrong please reply

ddeveau + 3 comments One iteration is definitely possible, but finding min,max,and sum values all at once is more intuitive than editing the sum value:

arr = list(map(int, input().strip().split(' '))) max=-sys.maxsize-1 min=sys.maxsize sum=0 for x in arr: sum+=x if x>max: max=x if x<min: min=x print (sum-max,sum-min)

backd00red + 4 comments Yeah, quite intutive but very few scalable. You're "lucky" the amount of values to take out from the total is just one. Otherwise you would have an ordered list of values filled as you iterate through the array, requiring O(nlogn) time. Hence I think the most scalable solution required O(nlogn) time, i.e. sorting the array in ascending order and taking the first n elements for the min sum and the last n for the max sum.

This is my code in swift, if it can help anyone:

import Foundation // Enter your code here let inputNumbers = readLine()!.components(separatedBy: " ").map { Int($0)! } let orderedNumbers = inputNumbers.sorted(by: <) let numbersToSum = 4 var min: UInt64 = 0 var max: UInt64 = 0 (0..<numbersToSum).forEach { let nextMinValue = orderedNumbers[$0] let nextMaxValue = orderedNumbers[orderedNumbers.count - ($0 + 1)] min += UInt64(exactly: nextMinValue)! max += UInt64(exactly: nextMaxValue)! } print("\(min) \(max)")

mariogonzalez + 0 comments very nice use of single array sort!

RogerB + 0 comments Not that it matters for inputs of this size, but there is a way to solve the problem in O(n) time for arbitrary k-sums, using quickselect.

Also, if you're concerned about the worst-case performance of quickselect, there's a version of quickselect with guaranteed O(n) time using the median-of-medians algorithm. Even cooler, there's introselect, which keeps both the low average-case constant factor of ordinary quickselect and the optimal worst-case complexity of median-of-medians.

Just figured I'd share. :)

agarwal_ankur09 + 2 comments If you use a min heap and a max heap you can solve this in n*log(m) time. 1. Given n integers. min and max sum of m values needed. 2. Create a min heap and a max heap of m values. 3. Iterate over n-m values updating both the heaps everytime in log(m) operations. 4. After the iteration just sum the two heaps in o(m) time each.

Total time:

(n-m) * 2 * log(m) + 2 * m

~ (2n - 2m) * log(m) ~ n*log(m)

= O(nlog(m))

RogerB + 2 comments There's also an O(n) solution. :)

grayedfox + 1 comment Could we see it? :)

zlatin_zlatev + 3 comments function main() { arr = readLine().split(' '); arr = arr.map(Number); var total=arr[0], min=arr[0], max=arr[0]; for (i=1; i<arr.length; i++) { total = total+arr[i]; if (min>arr[i]) { min=arr[i]; } if (max<arr[i]) { max=arr[i]; } } process.stdout.write("" + (total-max) + " " + (total-min)+"\n"); }

rajeevpodar + 4 comments #include <bits/stdc++.h> using namespace std; int main() { vector<unsigned long int> arr(5); unsigned long int minValue = ULONG_MAX; unsigned long int maxValue = 0; unsigned long int allSum = 0; for(int arr_i = 0; arr_i < 5; arr_i++){ cin >> arr[arr_i]; allSum += arr[arr_i]; minValue = min(minValue,arr[arr_i]); maxValue = max(maxValue,arr[arr_i]); } cout<<allSum - maxValue<<" "<<allSum - minValue<<endl; return 0; }

danghoangkieuhu1 + 0 comments Hey, man! Why you use vector arr(5) in there . Why not vector arr.

gouripanda4 + 0 comments Thankes man.

jeremy_r_jones91 + 0 comments Hi there. I'm curious as to why your code works with unsigned long int but not just int? Thanks

kaur_gursimar + 0 comments [deleted]kaur_gursimar + 3 comments It passes only a few test cases for me when i applied the same logic in c++.

t_rose + 1 comment I had the same issue as well, you need to use unsigned long int

jeremy_r_jones91 + 0 comments If you know the answer, could you explain why that is? As in, why unsigned long is needed instead of a traditional int?

abhijeetagnihot1 + 0 comments Same here

saryu21090 + 1 comment void miniMaxSum(vector<int> arr) { long int len = arr.size(); unsigned long int i,max=0,min=0,sum=0; for(i=0;i<len;i++){ sum += arr[i]; //arr.push_back(sum); } sort(arr.begin(), arr.end()); max= sum - arr[0]; min= sum - arr[len-1]; cout<<min<<"\t"; cout<<max; }

cosmopix38 + 0 comments [deleted]

verpra + 0 comments Not the most efficient solution (can be done in one pass), but really idiomatic in my opinion.

void miniMaxSum(const vector<int> &a) { unsigned long long tmp = std::accumulate(a.begin(), a.end(), 0L); auto result = std::minmax_element(a.begin(), a.end()); std::cout << tmp - *result.second << " " << tmp - *result.first; }

kaitoukid + 0 comments doesnt using a single for loop solve it in O(n)..why use O(nlog(m))

fernandomontoya1 + 0 comments [deleted]

intelligent_fun1 + 5 comments I did it this way by totalling the original array and just taking away each element from the total and appending the list with the result:

tot = sum(arr) res = [] for i in arr: res.append(tot - i) print("{} {}".format(min(res), max(res)))

kiennt23 + 0 comments Actually I find this smart

vinasatinfo + 0 comments that's quite awesome, really well done!

yarou + 0 comments Very clever, thanks for this.

mrcogllrdo + 0 comments The main issue with this is that it iterates through the list 4 times. There's a way to do it just twice. I'll show my code in a separate post.

andalltheworldi1 + 0 comments `result = [sum(arr) - i for i in arr] print(min(result), max(result))`

Condensed it.

devikabihani + 1 comment This code is not working... I'm doing it in java static void miniMaxSum(int[] a) { int max=0,min=1000000001,sum=0; for(int i=0 ; i<5 ; i++){

`if(a[i]>max){ max = a[i]; } if(a[i]<min){ min=a[i]; } sum=sum+a[i]; } System.out.print((sum-max) + " " + (sum-min)); }`

ricardo_ss + 0 comments [deleted]

lquintana0707 + 1 comment You can do it without iterations!

zlatin_zlatev + 3 comments Now that is something I would like to see. How can you avoid even single iteration over the input array?

grayedfox + 0 comments haha hey he said "iterations" (plural) - so, technically...

learndebian + 2 comments python 3

#!/bin/python3 import sys def miniMaxSum(arr): # Complete this function arr.sort() tot = sum(arr) print((tot - arr[-1]), (tot - arr[0])) if __name__ == "__main__": arr = list(map(int, input().strip().split(' '))) miniMaxSum(arr)

jjvannatta88 + 3 comments Well, that way you don't write out the loop yourself, but .sort() loops over the array O(n log n) times. The best I can find is one total iteration:

(in C)

unsigned long max = arr[0]; unsigned long min = arr[0]; unsigned long total = 0; for (int i = 0; i < arr_size; i++) { if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; total+=arr[i]; } printf("%ul %ul", total - max, total - min);

learndebian + 0 comments [deleted]novicewebdevelo1 + 0 comments Pretty neat

ravi_has_kiran + 0 comments printf("%ul %ul", total - max, total - min);

this should be

printf("%lu %lu", total - max, total - min);

meltthesnow1209 + 0 comments Well, the truth is sort() method was implemented including loop within.

dave_weernink + 1 comment `Arrays.sort(arr); final BigInteger minValue = BigInteger.valueOf(arr[0]+arr[1]+arr[2]+arr[3]); final BigInteger maxValue = BigInteger.valueOf(arr[1]+arr[2]+arr[3]+arr[4]); System.out.println(minValue+" "+maxValue); //unless you count the Arrays.sort as an iteration.`

the_sindaco + 0 comments You should valutate every item array as BigInteger for let it work.

rahul930 + 5 comments How do you come up with such solutions. I wrote a long ass code using if statements, but when i see your answer it is easy but it doesn't come to the mind when i am trying to look for a solution. I am a beginner, does it come with practise?

jmend + 2 comments Pretty much just comes with practice. As you program more you'll realize you can do more things without resorting to dealing with it case by case.

Also, the simple python solutions just come from doing a lot of things in one line. Don't worry about them, with time you'll realize what you can do all at once.

Just a note, just because a solution is short doesn't mean it's necessarily good programming or efficient. Eg. this solution is short, but inefficient (by a constant factor), and hard to read for those not as accustomed to things like this.

rahul930 + 0 comments yes i get what you are saying about this not being the best solution, although it still is better than doing it case by case.

Thank you for your feedback. I hope to have the same mindset someday when approaching problems.

olivierliu + 0 comments Hi jmend,

I definetly agree with you on my code being innefiecient, but I can explain it for everyone.

The first line is just reading the input - raw_input(), removing extra spaces at the beginning/end - .strip(), putting input in a list - .split(" ") and converting it all into ints - map().

The second line is adding all the integers together assigning it to a variable.

The third line is removing the largest number in the list to get the Min-sum, and removing the lowest number in the list to get the Max-sum.

olivierliu + 0 comments Hi Rahul, to answer your question, yes, it does come with some practice. If you have solved many problems, you will know how to deal with a "category" of problems.

When I was still a beginner, problems like these seemed impossible to me, but with some practice, you'll surely become better

Saipreeeeeeeee + 0 comments 9676305467....call we will discuss

Saipreeeeeeeee + 2 comments Na system ki rahul ekindi...Can u please provide me with anti rahul software :P

Uchandu_svct + 0 comments google chey

tarsum + 1 comment As everyone else steaded, practice, a lot of it.

And think that people forget is, you can write a clever solution but I will have to debug it or upgraded it. If you write everything in one line, and in C and Java you could, they don' relay on indentation.

There will be none who will want to work on that. Sometimes i write separate function just to keep the code out of the way, make it cleaner. There will be cases where program has a few lines of code and 2 or 3 times as much comments.

Algorithms are about elegant solutions, not clever one. KISS

chrisjaynes + 0 comments 90% of the problems on this site are more interested in their own cleverness than they are in being realistic problems.

And 90% of the solutions are more interested in their own cleverness than they are in being good code.

But this is what we have to deal with in interviews, nowadays. (sigh)

runcy + 6 comments 2 lines in python:

nums = [int(x) for x in input().strip().split(' ')] print(sum(nums) - max(nums), sum(nums) - min(nums))

olivierliu + 0 comments [deleted]paadanfel + 2 comments One line in PHP :)

`echo sprintf("%d %d", array_sum($arr)-max($arr), array_sum($arr)-min($arr));`

benheil + 0 comments That's sick

ady_touba_ngom + 0 comments why not put array_sum into a variable and do that calculation once. one liner are cool but not always synonym to performance

arjuneng2 + 2 comments # !/bin/python

import sys

arr = sorted(map(int, raw_input().strip().split(' ')))

a=sum(arr)

l=len(arr)

print a-arr[l-1], a-arr[0]

cryomick + 0 comments [deleted]zlatin_zlatev + 0 comments Sorting even on the most efficient algorythms is O(N log N).

You can do this without sorting - just find the total sum, min and max value. This way you get O(N) which is far better complexity.

wan_233 + 0 comments Two lines too, but looks scary((

def miniMaxSum(arr): sums = tuple(sum(arr[:i] + arr[i + 1:]) for i in range(len(arr))) print('%i %i' % (min(sums), max(sums)))

SwayZak + 0 comments Nice! I had a similar result:

def miniMaxSum(arr): min_int = sum(arr) - max(arr) max_int = sum(arr) - min(arr) print(min_int, max_int)

Anagha_Mulay + 2 comments How do we write it in python3? because raw_input is python2

olivierliu + 0 comments Hi Anagha, the way to write raw_input() in python 3 is just input()

Ardillo + 1 comment arr = sorted(list(map(int, input().split())))

print(sum(arr[:4]), sum(arr[1:]))

olivierliu + 0 comments [deleted]

rrajeshwari30 + 1 comment This is very crisp code!

olivierliu + 0 comments [deleted]

diego_amicabile + 2 comments Well done, better than mine I guess

arr = list(map(int, input().strip().split(' '))) min_a = sum([x for i, x in enumerate(arr) if i != arr.index(max(arr))]) max_a = sum([x for i, x in enumerate(arr) if i != arr.index(min(arr))]) print(min_a, max_a)

olivierliu + 0 comments [deleted]giridhar_trks + 1 comment int main(){ unsigned long long int a[5],max,min,sum=0; int i; scanf("%lld",&a[0]); max=a[0];min=a[0];sum=a[0]+sum; for(i=1;i<5;i++){ scanf("%lld",&a[i]); if(maxa[i]) min=a[i]; sum=sum+a[i]; } printf("%lld %lld",sum-max,sum-min); return 0; }

zlatin_zlatev + 0 comments Ugly as heck... but nice idea doing a single loop for input and finding sum, min and max.

sainanuj + 0 comments [deleted]jykl608 + 1 comment Thanks for your submission. I was wondering if the point of algorithms is to avoid using libraries if possible. Even tho it is a trivial example, shouldn't the sum of numbers be like

for(int i = 0; i < array.length; i++){ sum += array[i]; }

as opposed to "sum(array)"

Cheers

Maroseray + 0 comments I did this same exact solution but with substracting array[0] and array[array.length-1] to get the min/max total and it didnt pass! ha! I thought, my output was the same exact output as spec'd but it didnt pass? why? ha -

abhiramsatpute + 1 comment amazing approach! my code was of more than 10 lines

import sys from functools import reduce arr = list(map(int, input().strip().split(' '))) arr.sort() barr = arr.copy() barr.remove(arr[0]) d = reduce(lambda x,y:x+y,barr) arr.remove(arr[len(arr)-1]) c = reduce(lambda x, y: x + y, arr) print(c,d)

backd00red + 1 comment That's faaaar to messy man :)

abhiramsatpute + 1 comment I have learned so much in a month and now this code looks completely messed up.

davidKim + 0 comments how did you learn it? What source? cuz Ive never seen strip before

alanthony333 + 4 comments Did it in C. Is there a way to make it shorter?

int main() { int *arr = malloc(sizeof(int) * 5); for(int arr_i = 0; arr_i < 5; arr_i++){ scanf("%d",&arr[arr_i]); } long sum = 0; for(int i = 0; i < 5; i++) { sum = arr[i] + sum; } long lowest = sum, new_lowest = 0, highest = 0; for(int j = 0; j < 5; j++) { long a = sum - arr[j]; if(a < lowest) { lowest = a; new_lowest = a; } if(a > highest) { highest = a; } } printf("%ld %ld", new_lowest, highest); return 0; }

hackerdiwakar + 0 comments [deleted]hackerdiwakar + 3 comments int main() { int arr[5],small,large,arr_i; long int sum=0; small=arr[0]; large=arr[0]; for(arr_i = 0; arr_i < 5; arr_i++){ scanf("%d",&arr[arr_i]); if(small>arr[arr_i]) small=arr[arr_i]; if(large<arr[arr_i]) large=arr[arr_i]; sum=sum+arr[arr_i]; } printf("%ld %ld",sum-large,sum-small); return 0; }

ashishdalal_yes + 3 comments IT PASSED MY SAMPLE TEST ONLY...

kaitoukid + 0 comments did you copy paste it...in C you need to use malloc for the array. here he took static input

margdachelm + 0 comments you need to tweek the if statement to "if(small >arr[arr_i]|| arr_i==0)" and do the same with large

abhishek_satyam1 + 0 comments you have to initialize with the value of large=0 and some large value to small.

nandanhilsa90 + 0 comments [deleted]abhishek_satyam1 + 0 comments nice

daksh_dheeraj + 0 comments [deleted]zachbrogan + 0 comments No reason to use malloc here...

AyushSingh + 1 comment Great solution! Slightly different way of doing it below too:

from functools import reduce arr = list(map(int, input().strip().split(' '))) min = reduce((lambda x, y: x + y), sorted(arr)[:-1]) max = reduce((lambda x, y: x + y), sorted(arr)[1:]) print(str(min) + " " + str(max))

zlatin_zlatev + 1 comment Once again - sorting is increasing the complexity of the solution to O(N log N). In your example you are doing it twice, which if not optimised by compiler/runtime would result in two times poorer performance.

It could be solved without sorting with complexity O(N).

grayedfox + 0 comments One good reason for sorting the array, even if it adds another iteration, is that a sorted array allows us to do all sorts of other nifty things quite easily and without much effort, for example removing duplicate entries. Although possible without sorting, code readability wise, working with sorted data is (especially from a human perspective) often much easier!

stefan_pochmann + 0 comments Meh. Way too much pointless stuff. You don't need the

`strip`

, the`split`

parameter, and so many parentheses.`arr = map(int, raw_input().split()) s = sum(arr) print s - max(arr), s - min(arr)`

Another one:

`a = sorted(map(int, input().split())) print(sum(a[:-1]), sum(a[1:]))`

[deleted] + 0 comments Man that's pretty cool.

qd319 + 0 comments This code is brilliant! i am so silly that i literally add every 4 numbers together and see the sum.

janczak_marianna + 0 comments My version:

def miniMaxSum(arr): arr.sort() print(sum(arr[:4]),sum(arr[1:]))

ayushjain7398 + 0 comments my code in python but your code is more efficient: def miniMaxSum(arr): l=[] l.append(arr[1]+arr[2]+arr[3]+arr[4]) l.append(arr[0]+arr[2]+arr[3]+arr[4]) l.append(arr[1]+arr[0]+arr[3]+arr[4]) l.append(arr[1]+arr[2]+arr[0]+arr[4]) l.append(arr[1]+arr[2]+arr[3]+arr[0]) print(min(l),end=' ') print(max(l))

akonibrahim1 + 0 comments Yeah that looks sexy :-)

kmabignay1 + 0 comments here's mine :D arrx = [] for i,x in enumerate(arr): b = arr[0:] b.pop(i) arrx.append(sum(b)) sarrx = sorted(arrx) print (sarrx[0], sarrx[-1])

kalaayush15 + 0 comments Print requires one more bracket i.e print ((x-(max(lst))), (x-(min(lst)))) otherwise only the (x-(max(lst))) will run.

anu2anubhav + 0 comments You can do it in one iteration instead of three.

def miniMaxSum(arr): minarr = arr[0] maxarr = arr[0] sumarr = 0 for i in arr: if i < minarr: minarr = i if i > maxarr: maxarr = i sumarr = sumarr + i print sumarr-maxarr, sumarr-minarr

luboyswag + 0 comments Very good usage of map function.

ankushbairwa_221 + 0 comments [deleted]incetom77 + 0 comments But this is Python. It's a scripting language not code.

er_vikassri + 0 comments print(sum(sorted(list)[:-1]),sum(sorted(list)[1:]))

Kanahaiya + 0 comments Hello Coding Lover,

If you are looking for solution of hackerrank problems you can checkout the below link https://github.com/Java-aid/Hackerrank-Solutions.

It contains text solution as well as** video explaination**. Still there are many more solutions are in queue which needs to be added.

And if you are preparing for coding interview feel free to join out community here https://www.facebook.com/groups/codingip

Regards,

Kanahaiya Gupta

Git Hub URL | https://github.com/Java-aid/

LIKE US | https://www.facebook.com/javaaid/

SUBSCRIBE US | https://www.youtube.com/channel/UCx1hbK753l3WhwXP5r93eYA

m_den + 1 comment Or this way:

`def miniMaxSum(arr): arr.sort() print(sum(arr[0:len(arr)-1]), sum(arr[1:len(arr)]))`

Kanahaiya + 1 comment your solution is good but due to sorting it will take O(nlogn) time which can be optimized to O(n).

Here is the video explaination of my solution in O(n) time - https://youtu.be/6N86QrB_6n8

and you can find most of the hackerrank solutions with video explaination here- https://github.com/Java-aid/Hackerrank-Solutions

and many more needs to be addeed.

Regards,

Kanahaiya Gupta

Git Hub URL | https://github.com/Java-aid/

LIKE US | https://www.facebook.com/javaaid/

SUBSCRIBE US | https://goo.gl/jziyfZ

TELEGRAM LINK| @javaaid">@javaaid">https://web.telegram.org/#/im?p=@javaaid

m_den + 0 comments Agree.

appletopper1 + 0 comments [deleted]

wishicouldcode + 16 comments Java solution, in linear time. The idea is that always the max sum will be (totalSum - the min number) and min Sum will be (totalSum - maxNum)

public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); long[] nums = new long[5]; long max = 0, min= 0 , sum =0; nums[0] = max = min = sum = in.nextLong(); //Read the first value outside the loop, to handle min calculation for (int i = 1; i < 5; i++) { nums[i] = in.nextLong(); if(nums[i]>max) max = nums[i]; if(nums[i]<min) min = nums[i]; sum += nums[i]; } System.out.println( (sum - max) + " " + (sum - min)); } }

crazypan + 12 comments You can avoid the array

public static void main(String[] args) { Scanner in = new Scanner(System.in);

`long max, min, sum; sum = max = min = in.nextLong(); for(int i=1; i<5;i++){ long temp = in.nextLong(); sum += temp; if(max>temp){ if(min > temp) { min = temp; } } else { max = temp; } } System.out.print((sum -max) + " " + (sum - min)); }`

mayantiwari + 0 comments Nice one .

kencluff + 0 comments Nice.

xXlumeXx + 0 comments nice way :3

pandey_aditya97 + 0 comments nice and easy

jkeneth_jk + 3 comments Hello, what do this lines of code do?And why are you using Long instead of int?

sum = max = min = in.nextLong();

or

nums[0] = max = min = sum = in.nextLong();

amnhere + 0 comments Integer inputted by the system is assigned to sum, max and min. Long is being used in order to avoid overflow.

suyash_sreekumar + 0 comments Long allocates 64 bits whereas int allocates only 32 . It is mentioned explicitly in the program that it would be preffered that 64 bit be used.

manojkumarnov23 + 1 comment this line sum = max = min = in.nextLong(); assigns the input we give to all the htree variables max,min and sum as well

GDgranddeveloper + 0 comments but, what's reason of that? kindly explain in details.

iamkarthik49 + 1 comment But how

sum = max = min = in.nextLong();

works and what will be the value of min,max,sum....???? I tried the solution and it is not working...

souvik_bagchi + 0 comments all the values will be equal to the next input

ravi_patel16 + 0 comments nice one

vkokielov + 0 comments If min > temp, isn't max>temp by assumption?

DanYoo940 + 0 comments why do you equalize max min and sum for = in.nextLong

zlatin_zlatev + 0 comments Absolutely true - we don't even need the array.

duraivel1198 + 0 comments is good, but for the given problem we have to solve the algorithm firt, for example {1,2,3,4,5} Solution: 2+3+4+5=14 1+3+4+5=13 1+2+4+5=12 1+2+3+5=11 1+2+3+4=10 Then we have to find the min&max{14,13,12,11,10}

GDgranddeveloper + 0 comments [deleted]

randy_evered + 0 comments Oh! I did not think to change the scanning code to read longs... I was trying to do it with int array, and failing test 4. :) Thank you. Great discussions here.

randy_evered + 2 comments `Scanner in = new Scanner(System.in); List<Long> a = new ArrayList<>(); for(int i = 0; i < 5; i++) a.add(new Long(in.nextLong())); long min = a.stream().mapToLong(f -> f).min().getAsLong(); long max = a.stream().mapToLong(f -> f).max().getAsLong(); long sum = a.stream().mapToLong(f -> f).sum(); System.out.println((sum - max) + " " + (sum - min));`

mflorenciaperei1 + 0 comments Best approach for Java.

manojkumarnov23 + 0 comments a.stream().mapToLong(f -> f).min().getAsLong(); Can you please elaborate what this line does??

kevinq93 + 0 comments [deleted]hiddencoder + 0 comments import java.util.*; // for beginner guyes

psdudeman39 + 0 comments Thanks, I was coming up with a more complicated procedure

VaZark + 1 comment This works under the assumption that are inputs are non-negative. It would become erroneous when negative integers are introduced.

mflorenciaperei1 + 0 comments The problem states that there're all positive: "Given five positive integers..."

AdYaNsH + 2 comments Simplest Java solution

public static void main(String[] args) { Scanner in = new Scanner(System.in); long[] arr = new long[5]; for(int arr_i=0; arr_i < 5; arr_i++){ arr[arr_i] = in.nextLong(); } Arrays.sort(arr); System.out.println(arr[0] + arr[1] + arr[2] + arr[3] + " " + (arr[1] + arr[2] + arr[3] + arr[4])); }

crazypan + 2 comments Yes, this is a simple solution for a starter. Now try to optimize it. Say instead of 5 numbers you are given 5,000,000 numbers. Will this work? What can you do to improve your solution?

AdYaNsH + 1 comment This solution is for just this problem because it is specified that we are just given 5 numbers.If we are given more numbers then we'll have to loop it and i hava tried to avoid a loop.

garapatiraja1995 + 0 comments It really is an awesome solution.....i wish i can put a thumbs up emoji....haha

CodeAcharya + 0 comments We use following loops for 5000000 numbers

Arrays.sort(arr); for(int i = 0; i<n-1;i++){ min += arr[i]; max += arr[i+1]; }

or

Arrays.sort(arr); for(int j=0;j<n-1;j++) min +=arr[j]; for(int i=1;i<n;i++) max +=arr[i]; System.out.printf(min+" "+max);

engg_priya01 + 1 comment But this is failing for other test cases having big values. Could you please explain.

Babuljha15 + 0 comments please declare min and max as long.

souvik_bagchi + 0 comments Ele ffing gant !! Beautiful code.

nonatorw + 0 comments [deleted]nonatorw + 1 comment Based on your solution, I do this. Thanks!

import java.util.Scanner; public class Solution4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); long sum = 0; long min = 2147483647; long max = 0; long tmp = 0; for (int i = 0; i < 5; i++) { tmp = in.nextInt(); max = tmp > max ? tmp : max; min = tmp < min ? tmp : min; sum += tmp; } // System.out.println("Max: " + max + "\nMin: " + min); System.out.println((sum - max) + " " + (sum - min)); in.close(); } }

pangaribuansusy + 1 comment would you explain what does long min = 2147483647; mean?

nonatorw + 1 comment This is the max value permitted to an Integer. I used this "technique" when I used to develop using COBOL language (same as HIGH-VALUES), to oblige any value compared with this be lesser than the HIGH-VALUE, or 2147483647.

nonatorw + 0 comments I notice now that I made a little fuss: when I was coding this, all the variables are "int", but in the tests of commit, various test cases failed because the values used are in long format. So I change the type of all variables to long, but I didn't change the highest value of min to the highest value of a long type.

sudheera_nv + 0 comments nice one

anilkumaryadav91 + 0 comments thanx..

tajnology + 0 comments Exactly my solution, though I did it in c

#include <stdio.h> #include <limits.h> int main(){ int inp,largest=0,smallest=INT_MAX; unsigned sum=0; for(int i = 0; i < 5; i++){ scanf("%d",&inp); if(inp>largest) largest = inp; if(inp<smallest) smallest = inp; sum+=inp; } printf("%u %u\n",sum-largest,sum-smallest); }

artyomzolotover1 + 0 comments good solution, i made the same one. But best practice is to use array length for loop condition, as

**for (int i = 0; i < array.length; i++){}**code__raider + 0 comments what if, we do it by sorting the array in ascending order and then calculate the sum of first four elements and last four elements in order to find the min & max values...

luumanhlapdi + 7 comments My solution in c# :D

string[] arr_temp = Console.ReadLine().Split(' '); long[] arr = Array.ConvertAll(arr_temp, Int64.Parse); long result1 = 0; long result2 = 0; long max = arr.Max(); long min = arr.Min(); for (int i = 0; i < arr.Length; i++) { result1 += arr[i]; result2 += arr[i]; } Console.WriteLine("{0} {1}",result1 - max,result2 - min);

programmer37 + 1 comment this is actually excellent, been coding it myself before looking at the discussion :D

luumanhlapdi + 0 comments Thanks, bro. :D

c_wituchowski + 1 comment I like this a lot, I had 2 for loops to get min and max separately but this is much simpler.

zhakalen + 0 comments If I'm not mistaken this solution uses 4 loops to solve the problem (:

Array.ConvertAll(arr_temp, Int64.Parse); <--- This is a loop. arr.Max(); <--- This is also a loop. arr.Min(); <--- And this is also a loop. for (int i = 0; i < arr.Length; i++) <--- This we know is a loop :D

IS201601013 + 0 comments [deleted]Stijn_van_horen1 + 2 comments you don't even need a for loop in C#, here is my solution:

static void Main(String[] args) { string[] arr_temp = Console.ReadLine().Split(' '); long[] arr = Array.ConvertAll(arr_temp, Int64.Parse); long minSum = arr.Sum() - arr.Max(); long maxSum = arr.Sum() - arr.Min(); Console.WriteLine("{0} {1}",minSum, maxSum); }

grayedfox + 0 comments actually, you loop through this array 4 times (not including the original ConvertAll to parse everything to Int64...). How do you think arr.Sum() and arr.Max() work ;)

tat_vam_asi + 1 comment Originally thought of implementing this idea, without a loop but gigantic test cases were failing because array.Sum() somehow was too big. Had to change the algorithm to a loop to make a lot of test cases pass.

dipasree_g + 0 comments same here.

grayedfox + 0 comments Nice solution but you loop through the array 3 times here: min() and max() methods loop through entire array to find those values - you could do the whole thing in your for loop with a bit of tweaking ;) but kudos none the less

h0nja + 0 comments You dont need two result longs:

long sum = 0; long min = arr.Min(); long max = arr.Max(); for (int i = 0; i<arr.Length; i++){ sum = sum + arr[i]; } Console.WriteLine("{0} {1}",sum-max,sum-min);

milesic_mladen + 0 comments long[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt64(arrTemp)) ; Array.Sort(arr);

long min = (arr[0]+arr[1]+arr[2]+arr[3]); long max = (arr[1]+arr[2]+arr[3]+arr[4]); Console.WriteLine(min + " " + max);`why not just sort it and add the first 4 then last 4? the problem stated it's always an array of 5`

vhudjan + 2 comments Java solution:

long[] array = {a,b,c,d,e};

Arrays.sort(array);

long min = 0; long max = 0;

for(int i = 0; i<4;i++){

`min+=array[i]; max+= array[i+1];`

}

System.out.print(min + " " + max);

developer_akhil1 + 2 comments why sorting? just add all nums in first input loop and in next loop find min and max

jarvian + 1 comment i think both are same

developer_akhil1 + 2 comments I don't think both are same. Sorting makes it solution complex(considering we are not using in-built sorting method). Also sorting will give nlogn complexity and finding min and max in next loop makes O(n) + O(nlogn) = O(nlogn) total complexity of this solution. Correct me if I am wrong.

jarvian + 0 comments yeah

tylergatta + 1 comment Since the problem states that the input will always be exactly 5 integers, is this a reasonable concern?

agodfrey3 + 2 comments You can sort the numbers in nlogn time assuming you use quicksort, and since the size will always be 5, you can add the values in constant time. You just add the first four to get the smallest sum, and the last 4 to get the largest sum.

agodfrey3 + 0 comments buy you can do it in linear time without sorting, so take your pick.

RajaRaghav + 1 comment isn't quicksort algorithm's wrost case have n^2 complexity ? correct me if i'm wrong.

kimble00550117 + 1 comment Only if you pick a bad pivot, which usually doesn't happen.

RajaRaghav + 0 comments yes. you're right.

olivierliu + 0 comments I did exactly that:

lst = map(int,raw_input().strip().split(' ')) x = sum(lst) print (x-(max(lst))), (x-(min(lst)))

vigneshwar028 + 0 comments what you actually mean i+1 ? i mean how you know the index number i+1 will be max?

suraneti_rod + 2 comments Python is the best

x = sum(arr) minValue = x - max(arr) maxValue = x - min(arr) print(minValue, maxValue)

tom_wagner + 0 comments 🔥🔥🔥🔥🔥

basillatif + 0 comments Great use of the in-built sum, max, and min methods in Python.

Ramzes + 7 comments what do you think about this solution in java:

public static void main(String[] args) { Scanner in = new Scanner(System.in); long a = in.nextLong(); long b = in.nextLong(); long c = in.nextLong(); long d = in.nextLong(); long e = in.nextLong(); SortedSet<Long> sortedSet = new TreeSet(); sortedSet.add(b + c + d + e); sortedSet.add(a + c + d + e); sortedSet.add(a + b + d + e); sortedSet.add(a + b + c + e); sortedSet.add(a + b + c + d); System.out.println(sortedSet.first() + " " + sortedSet.last()); }

wsmithsrs + 0 comments That's actually an interesting way to go about it.

carlo_a_kind + 1 comment That is interesting. However I think the time complexity for this would still be the same as sorting, O(NlogN), since you are performing an insertion into the tree for each element and each insertion takes logN time.

Ramzes + 0 comments you're right.

sahilshetye + 1 comment why would you use sortedset? if after adding you could search for maximum amongst them?

imtheone + 1 comment Please tell me how we can find biggest anad smaller no. without use of sortedset .?

ResamVi + 1 comment You initialize a

`biggest`

variable iterate the array once. When you've found a bigger one you change it accordingly. This is`O(n)`

.int biggest = Integer.MIN_VALUE; for(int i = 0; i < array.length; i++) { if(array[i] > biggest) biggest = array[i]; }

Insertion into a SortedSet is

`O(log n)`

(Source) and with`n`

insertion this would be`O(n * log n)`

which is asymptotically worse.imtheone + 1 comment What if we skip this line . I guess the iteration will still find out the biggest. How this MIN_VALUE & MAX_VALUE works .?

int biggest = Integer.MIN_VALUE;

ResamVi + 1 comment Simply "skipping" won't quite make this work. In this exercise each integer was in the inclusive range of

`[1, 10^9]`

so setting`biggest`

would have sufficed as well.In more general terms, if we had to assume the elements in the arrays are integer we have numbers ranging between

`[-2^31, 2^31 - 1]`

or in other words`[Integer.MIN_VALUE, Integer.MAX_VALUE]`

.If you would simply "skip" this line, let's say you would set

`biggest`

to zero then passing your function the array:`[-1,-3,-1,-5]`

would yield in 0 being the biggest, even though the number doesn't even appear in the array.

PraveenaT + 1 comment SortedSet sortedSet = new TreeSet(); why did u use capital L in long rather than data type

sahilshetye + 0 comments Long is wrapper data-type. long is a primitive data-type. Long can be seen as Java Object. Long class has various usefull functions Like toString,compare defined in the class. Generally these are not available to long data-type. Also underneath Long it does implement long.

Various other primitive vs Wrapper data types are: int vs Integer char vs Character etc etc

PraveenaT + 1 comment public static void main(String[] args) { Scanner in = new Scanner(System.in); long a = in.nextLong(); long b = in.nextLong(); long c = in.nextLong(); long d = in.nextLong(); long e = in.nextLong(); SortedSet p = new TreeSet(); p.add(b+c+d+e); p.add(a+c+d+e); p.add(a+b+d+e); p.add(a+b+c+d); System.out.println(p.first() +" " +p.last()); }

`this code is not working 2,6,8,9,11 can anyone help me out?`

sahilshetye + 0 comments you forgot to write p.add(a+b+c+e)

srishtiamin + 0 comments I do not think this is right way as if there are many numbers.

kamlesh9707 + 0 comments Thats why java is my favourite...

Kanahaiya + 1 comment My solution in java-

public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); long min,max,sum=0; min=in.nextLong(); max=min; sum=min; for(int i=0;i<4;i++){ long a = in.nextLong(); sum+=a; if(a<min){ min=a; } if(a>max){ max=a; } } System.out.print((sum-max)+" "+(sum-min)); } }

Saurabh4learning + 0 comments nice one 👏👏

marinskiy + 0 comments Here is

**Python 3**solution from my HackerrankPractice repository:arr = list(map(int, input().split())) print(sum(arr) - max(arr), sum(arr) - min(arr))

Feel free to ask if you have any questions :)

camkida + 6 comments javascript

function sum(x, y) { return Number(x) + Number(y); } function main() { var a_temp = readLine().split(' '); const sorted = a_temp.sort(); const min = sorted.slice(0, 4).reduce(sum, 0); const max = sorted.slice(1, 5).reduce(sum, 0); console.log(min, max); }

ngdana1 + 0 comments I often overthink these algorithms. It makes sense that the numbers from index 0 - 4 would be less than 1 - 5!

andythedandyone + 0 comments [deleted]boomerboxer_real + 0 comments Here is my approach.

arr.sort((a,b) => a-b); console.log(String(arr.slice(0,4).reduce((a,b)=>a+b)) + ' ' + String(arr.slice(1,5).reduce((a,b)=>a+b)));

mlederkremer + 0 comments brilliant

hezardx + 1 comment here is mine

let min = Math.min.apply(null, arr), max = Math.max.apply(null, arr); let sum = arr.reduce((prev, curr) => prev + curr); console.log(sum - max, sum - min);

scaryguy + 0 comments If you're using ES6 syntax, you can simply use spread operator within

`Math.max`

and`Math.min`

functions' argument like this:Math.min(...arr); Math.max(...arr);

No need to use ugly

`apply`

:\

virginielgb + 1 comment Nice. I went for nothing more than

`sort`

and because it's a small array, manual log:function main() { const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10)); arr.sort(); console.log((arr[0]+arr[1]+arr[2]+arr[3])+' '+(arr[1]+arr[2]+arr[3]+arr[4])); }

emailbevo + 0 comments sort() doesn't work as you would expect with integers, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

yefremov + 0 comments Code in JavaScript:

function main() { var a_temp = readLine().split(' ').map(Number); var sum = a_temp.reduce((acc, value) => acc += value); var min = sum - Math.max.apply(null, a_temp); var max = sum - Math.min.apply(null, a_temp); console.log(min + " " + max); }

Sort 1936 Discussions, By:

Please Login in order to post a comment