Min Max Riddle

  • + 0 comments

    in swift

    func riddle(arr: [Int]) -> [Int] {
        let n = arr.count
        var maxWin = [Int](repeating: 0, count: n)
        var stack = [(index: Int, value: Int)]()
        var leftBoundaries = [Int](repeating: 0, count: n)
        var rightBoundaries = [Int](repeating: n, count: n)
    
         for i in 0..<n {
             while !stack.isEmpty && stack.last!.value >= arr[i] {
                    stack.popLast()
                }
        leftBoundaries[i] = stack.isEmpty ? 0 : stack.last!.index + 1
        stack.append((index: i, value: arr[i]))
            }
    
    stack.removeAll()
    
    for i in stride(from: n - 1, through: 0, by: -1) {
            while !stack.isEmpty && stack.last!.value >= arr[i] {
                stack.popLast()
      }
      rightBoundaries[i] = stack.isEmpty ? n : stack.last!.index
      stack.append((index: i, value: arr[i]))
    }
    
    for i in 0..<n {
            let windowSize = rightBoundaries[i] - leftBoundaries[i]
      maxWin[windowSize - 1] = max(maxWin[windowSize - 1], arr[i])
    }
    
    for i in stride(from: n - 2, through: 0, by: -1) {
            maxWin[i] = max(maxWin[i], maxWin[i + 1])
    }
    
            return maxWin
    }