Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Created September 12, 2017 09:27
Show Gist options
  • Save arashkashi/9a74a2c1f36aa11babfca602394513b2 to your computer and use it in GitHub Desktop.
Save arashkashi/9a74a2c1f36aa11babfca602394513b2 to your computer and use it in GitHub Desktop.
Max double slice
public func solution(_ A : inout [Int]) -> Int {
if A.count <= 3 { return 0 }
// write your code in Swift 3.0 (Linux)
// handle special cases
var toRight: [Int] = Array(repeating: 0, count: A.count - 2)
var toLeft: [Int] = Array(repeating: 0, count: A.count - 2)
for (index, _) in A.enumerated() {
if index == 0 || index == A.count - 1 { continue }
let leftToRightIndex: Int = index - 1
if index == 1 {
toLeft[leftToRightIndex] = 0
} else {
toLeft[leftToRightIndex] = max(0, max(A[index - 1], A[index - 1] + toLeft[leftToRightIndex - 1]))
}
let rightToLeftIndex: Int = toRight.count - index
if rightToLeftIndex == toRight.count - 1 {
toRight[rightToLeftIndex] = 0
} else {
toRight[rightToLeftIndex] = max(0, max(A[A.count - index - 1 + 1], A[A.count - index - 1 + 1] + toRight[rightToLeftIndex + 1]))
}
}
var result: Int = 0
for (i, item) in toRight.enumerated() {
if toRight[i] + toLeft[i] > result { result = toRight[i] + toLeft[i] }
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment