• + 0 comments

    SWIFT

    func fairRations(B: [Int]) -> String {
        // Write your code here
        var oddIndex: [Int] = [Int]()
        var oddDict: [Int: Int] = [:]
        var steps: Int = 0
        
        for index in 0 ... B.count - 1 {
            if B[index] % 2 == 1 {
                oddIndex.append(index)
                oddDict[index] = index
            }
        }
        
        if oddIndex.count % 2 == 1 { return "NO" }    
        
        while(oddIndex.count > 1) {
          var currentOddIndex: Int = oddIndex.first!
          steps += 2
          let nextOddIndex: Int = currentOddIndex + 1
            if oddDict[nextOddIndex] == nil {
                oddIndex[0] = nextOddIndex
                oddDict.removeValue(forKey: currentOddIndex)
                oddDict[nextOddIndex] = nextOddIndex
                continue
            }
              
            while(currentOddIndex <= nextOddIndex) {
                oddIndex.removeFirst()
                oddDict.removeValue(forKey: currentOddIndex)
                currentOddIndex += 1
            }
        }
            
        return String(steps)
    }