1

I have a list of prices and want to find the minimum price EXCLUDING the first element (this is a subset of another problem on HackerRank).

My version is too slow and times out. I suspect this is due to my ArraySlice.

Here is my (working) code:

func calculateMins(prices: [Int]) {
    for j in 1..<prices.count  {
        let lowestPreviousPrice = prices[1...j].min()!
        print (lowestPreviousPrice)
    }
}

calculateMins(prices: [4,8,2,4,3])

Is there a better performing version of this, perhaps one that does not use an ArraySlice?

4
  • 1
    Why just you can't use Array.min() function? Commented Jan 29, 2019 at 9:45
  • Needs to be a subset of the array (I've overly reduced the problem) I'll change this example to excluding the first element instead. Commented Jan 29, 2019 at 9:47
  • What will be the output? Commented Jan 29, 2019 at 9:48
  • Let's just take it as the min of an array, EXCLUDING the first element. Have updated the question. Commented Jan 29, 2019 at 9:50

4 Answers 4

6

Just use dropFirst() function.

var array = [1,8,2,4,3]
var array2 = array.dropFirst() // Returns a subsequence containing all but the first element of the sequence.
array2.min() // 2
Sign up to request clarification or add additional context in comments.

Comments

2

Why not keep it simple

func calculateMins(prices: [Int]) {
    var min = Int.max
    for i in 1..<prices.count {
        if prices[i] < min { min = prices[i] }
    }
    print(min)    
}

Comments

2

You have few options to solve this issue.

//Default way
prices.dropFirst().min()

//Functional way
prices.dropFirst().reduce(Int.max, { min($0, $1) })

Comments

1

You could also use suffix, which is quite same as dropFirst that this version could crash if in case array is empty.

array.suffix(from: 1).min()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.