Skip to content

Instantly share code, notes, and snippets.

@lucasrpb
Last active November 13, 2025 14:57
Show Gist options
  • Select an option

  • Save lucasrpb/94d012ce82ee5f8201506f7401765ced to your computer and use it in GitHub Desktop.

Select an option

Save lucasrpb/94d012ce82ee5f8201506f7401765ced to your computer and use it in GitHub Desktop.
object MaxStableSubarray {
def isStable(a: Array[Int], y: Int): Boolean = {
var min = Int.MaxValue
var max = Int.MinValue
for(i<-0 until a.length){
val e = a(i)
if(e > max){
max = e
}
if(e < min){
min = e
}
}
max - min <= y
}
def main(args: Array[String]): Unit = {
val arr = Array(1, 2, 3, 4)
val m = arr.length
var maxLenSubArray = 0
val y = 2
for(i<-0 to m){
for(j<-0 to m){
val slice = arr.slice(i, j)
if(!slice.isEmpty && isStable(slice, y) && slice.length > maxLenSubArray){
maxLenSubArray = slice.length
}
}
}
println(s"max n-stable array length is: ${maxLenSubArray}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment