Skip to content

Instantly share code, notes, and snippets.

@kell18
Created July 24, 2019 20:19
Show Gist options
  • Save kell18/a7b5d830b661fa97ba186290c7296a3e to your computer and use it in GitHub Desktop.
Save kell18/a7b5d830b661fa97ba186290c7296a3e to your computer and use it in GitHub Desktop.
sealed trait Slice extends Product with Serializable {
def length: Int
}
object Slice {
def empty: Slice = EmptySlice
}
case class HalfSlice(num: Int, ind: Int) extends Slice {
override def length = 1
}
case class FullSlice(even: Int, odd: Int, length: Int) extends Slice {
def isBelongsToSlice(num: Int, ind: Int) = if (ind % 2 == 0) num == this.even else num == this.odd
def increaseLength: FullSlice = this.copy(length = length + 1)
}
case object EmptySlice extends Slice {
override def length = 0
}
def maxSwitch(a: Array[Int]): Int = if (a.length < 3) a.length else {
val (prevMaxLen, lastSlice) = a.zipWithIndex.foldLeft(0 -> Slice.empty) {
case ((maxSliceLen, EmptySlice), (num, ind)) =>
Math.max(maxSliceLen, 1) -> HalfSlice(num, ind)
case ((maxSliceLen, HalfSlice(sNum, sInd)), (num, ind)) =>
Math.max(maxSliceLen, 2) -> (
if (sInd % 2 == 0) FullSlice(sNum, num, 2) else FullSlice(num, sNum, 2)
)
case ((maxSliceLen, slice@FullSlice(even, odd, sLen)), (num, ind)) if slice.isBelongsToSlice(num, ind) =>
if (slice.length + 1 > maxSliceLen) (sLen + 1) -> slice.increaseLength
else maxSliceLen -> slice.increaseLength
// new num does't belongs to current slice
case ((maxSliceLen, slice@FullSlice(even, odd, sLen)), (num, ind)) =>
Math.max(maxSliceLen, 2) -> (
if (ind % 2 == 0) FullSlice(num, odd, 2) else FullSlice(odd, num, 2)
)
case x => sys.error(s"something went wrong: $x")
}
Math.max(prevMaxLen, lastSlice.length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment