How to get the number of days needed to wait after a day (a[i]) gets warmer given an array of temperatures in Swift

1 Answer

0 votes
import Foundation

// Print all elements in an array
func printArray(_ arr: [Int]) {
    print(arr.map { String($0) }.joined(separator: " "))
}

// Calculate how many days you must wait for a warmer temperature
func numberOfDaysToWait(_ temperatures: [Int]) -> [Int] {
    let size = temperatures.count
    var result = Array(repeating: 0, count: size)
    var stack: [Int] = []   // stack of indices

    for i in 0..<size {

        // While the current temperature is warmer than the temperature
        // at the index stored at the top of the stack:
        while let last = stack.last, temperatures[i] > temperatures[last] {
            let idx = stack.removeLast()
            result[idx] = i - idx
        }

        // Push the current index onto the stack
        stack.append(i)
    }

    // Remaining indices in the stack have no warmer future day
    // (result already contains zeros)
    return result
}

// Example usage:
let temperatures = [82, 84, 81, 58, 85, 89, 75, 71]

// 82 -> 84 = 1
// 84 -> 81 -> 58 -> 85 = 3
// 81 -> 58 -> 85 = 2
// 58 -> 85 = 1
// 85 -> 89 = 1
// 89 -> 75 -> 71 = 0
// 75 -> 71 = 0

let result = numberOfDaysToWait(temperatures)

printArray(result)



/*
run:

1 3 2 1 1 0 0 0

*/

 



answered 14 hours ago by avibootz

Related questions

...