Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created March 1, 2019 13:38
Show Gist options
  • Save jmcd/e655bb0706e67fb64b357ebc5f495981 to your computer and use it in GitHub Desktop.
Save jmcd/e655bb0706e67fb64b357ebc5f495981 to your computer and use it in GitHub Desktop.
func largestSquare(_ s: String, width: Int) -> Int {
let bits = s.map { $0 == "1" }
let height = bits.count/width
let longestLen = (0..<bits.count).reduce(0) { (curLongestLen, i) in
let maxLen = min(width - i%width, height - i/width)
let firstLenWhereAllBitsNotSet = (1...maxLen).first(where: { len in
!(0..<len).allSatisfy { n in
bits[i + width*(len-1) + n] && bits[i + (len-1) + width*n]
}
})
let lastLenWhereAllBitsSet = (firstLenWhereAllBitsNotSet ?? maxLen+1) - 1
return max(curLongestLen, lastLenWhereAllBitsSet)
}
return longestLen*longestLen
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment