Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Mini-Max Sum One Test Case Failed - HackerRank

Before anything else, I checked if this kind of question fits Stackoverflow, and based on one similar question (javascript) and from this question: https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on -- it does.

So here it goes. The challenge is pretty simple, in my opinion:

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, . Our minimum sum is and our maximum sum is . We would print

16 24

Input Constraint: 1 <= arr[i] <= (10^9)

My solution is pretty simple. This is what I could do best:

func miniMaxSum(arr: [Int]) -> Void {
    let sorted = arr.sorted()
    let reversed = Array(sorted.reversed())
    var minSum = 0
    var maxSum = 0

    _ = sorted
        .filter({ $0 != sorted.last!})
        .map { minSum += $0 }  
    _ = reversed
        .filter({ $0 != reversed.last!})
        .map { maxSum += $0 }    

    print("\(minSum) \(maxSum)")
}

As you can see, I have two sorted arrays. One is incrementing, and the other one is decrementing. And I'm removing the last element of the two newly sorted arrays. The way I remove the last element is using filter, which probably creates the problem. But from there, I thought I could get easily the minimum and maximum sum of the 4 elements.

I had 13/14 test cases passed. And my question is, what could be the test case in which this solution will likely to fail?

Problem link: https://www.hackerrank.com/challenges/mini-max-sum/problem

like image 846
Glenn Posadas Avatar asked Jun 22 '26 07:06

Glenn Posadas


1 Answers

Here

_ = sorted
    .filter({ $0 != sorted.last!})
    .map { minSum += $0 }  

your expectation is that all but the largest element are added. But that is only correct it the largest element is unique. (And similarly for the maximal sum.)

Choosing an array with all identical errors makes the problem more apparent:

miniMaxSum(arr: [1, 1, 1, 1, 1])
// 0 0 

A simpler solution would be to compute the sum of all elements once, and then get the result by subtracting the largest respectively smallest array element. I'll leave the implementation to you :)

like image 153
Martin R Avatar answered Jun 24 '26 21:06

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!