You are viewing a single comment's thread. Return to all comments →
scala using just recursion (tailrec is optional):
import scala.annotation.tailrec import scala.io.StdIn object Solution { private def solve(a: Array[Int], d: Int, m: Int): Int = { val n = a.length def isValid(i: Int, ad: Int, m: Int): Boolean = ad <= a(i) && a(i) <= (ad + m) @tailrec def getLeft(i: Int, ad: Int, m: Int): Int = { if (i < 0) 0 else if (!isValid(i, ad, m)) (i + 1) else getLeft(i - 1, ad, m) } @tailrec def getRight(i: Int, ad: Int, m: Int): Int = { if (n <= i) (n - 1) else if (!isValid(i, ad, m)) (i - 1) else getRight(i + 1, ad, m) } getRight(d + 1, a(d), m) - getLeft(d - 1, a(d), m) + 1 } def main(args: Array[String]): Unit = { val in = Iterator .continually(StdIn.readLine()) .takeWhile(null != _) .map(_.trim) in.next() val a = in.next().split(' ').map(_.toInt) val q = in.next().toInt val queries = (1 to q) .map(_ => in.next().split(' ').map(_.toInt)) .map(dm => solve(a, dm.head, dm.last)) .foreach(println) } }
Seems like cookies are disabled on this browser, please enable them to open this website
Stock Prediction
You are viewing a single comment's thread. Return to all comments →
scala using just recursion (tailrec is optional):