Skip to content

Instantly share code, notes, and snippets.

@gabrielepalma
Created November 15, 2018 18:45
Show Gist options
  • Save gabrielepalma/433077edf0dba7385063d9c65a9c4538 to your computer and use it in GitHub Desktop.
Save gabrielepalma/433077edf0dba7385063d9c65a9c4538 to your computer and use it in GitHub Desktop.
import Foundation
// Complete the arrayManipulation function below.
func arrayManipulation(n: Int, queries: [[Int]]) -> Int {
var items = Array(repeating: 0, count: n)
print("\(items)")
for query in queries {
let s = query[0] - 1
let e = query[1]
let k = query[2]
items[s] = items[s] + k
if (e<items.count) { items[e] = items[e] - k }
}
var current = 0
var max = -1
for i in 0..<items.count {
current = current + items[i]
if current > max {
max = current
}
}
return max
}
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let nmTemp = readLine() else { fatalError("Bad input") }
let nm = nmTemp.split(separator: " ").map{ String($0) }
guard let n = Int(nm[0].trimmingCharacters(in: .whitespacesAndNewlines))
else { fatalError("Bad input") }
guard let m = Int(nm[1].trimmingCharacters(in: .whitespacesAndNewlines))
else { fatalError("Bad input") }
let queries: [[Int]] = AnyIterator{ readLine() }.prefix(m).map {
let queriesRow: [Int] = $0.split(separator: " ").map {
if let queriesItem = Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) {
return queriesItem
} else { fatalError("Bad input") }
}
guard queriesRow.count == 3 else { fatalError("Bad input") }
return queriesRow
}
guard queries.count == m else { fatalError("Bad input") }
let result = arrayManipulation(n: n, queries: queries)
fileHandle.write(String(result).data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment