title: I am gettting TLE on Hackerrank how can I optimize the Scala code? I am trying to solve the maximum element problem on hackerrank
body: <pre><code>def getMax(operations: Array[String]): ArrayBuffer[Int] = {
      // Write your code here
          var a: ArrayBuffer[Int] = mutable.ArrayBuffer()
          val s = mutable.Stack[Int]()
          val check_1 = (s:String) =&gt; s.contains(&quot; &quot;) &amp;&amp; (s.substring(0,1).toInt.equals(1))
          val check_2 = (s:String) =&gt; (s.contains(&quot; &quot;) || !s.contains(&quot; &quot;)) &amp;&amp; (s.substring(0,1).toInt.equals(2))
          val check_3 = (s:String) =&gt; (s.contains(&quot; &quot;) || !s.contains(&quot; &quot;)) &amp;&amp; (s.substring(0,1).toInt.equals(3))
          val check_4 = (s:String) =&gt; s.substring(0,1).toInt.equals(1)
          for(i &lt;- operations) yield {
              i match {
                  case w if(check_1(i)) =&gt; s.push(i.substring(2,(i.length)).toInt)
                  case d if(check_2(i)) =&gt; s.pop
                  case q if(check_3(i))=&gt; a :+= s.max
                  case t if(check_4(i)) =&gt; s.push(i.substring(1,(i.length)).toInt)
                  case _ =&gt;
                  }
              }
              a
      }
  </code></pre>
  <p>and</p>
  <pre><code>  def getMax(ops:Array[String]): Array[Int] ={
      var a: Array[Int] = Array()  // This is the cache for storing the max
      val s = mutable.Stack[Int]()
      for(i &lt;- ops) {
        if(i.contains(&quot; &quot;) &amp;&amp; (i.substring(0,1).toInt.equals(1)))  s.push(i.substring(2,(i.length)).toInt)
        else if((i.contains(&quot; &quot;) || !i.contains(&quot; &quot;)) &amp;&amp; (i.substring(0,1).toInt.equals(2))) s.pop
        else if((i: .contains(&quot; &quot;) || !i.contains(&quot; &quot;))&amp;&amp; (i.substring(0,1).toInt.equals(3))) a :+= s.max
        else if(i.substring(0,1).toInt.equals(1)) s.push(i.substring(1,(i.length)).toInt)
      }
      a
    }
  </code></pre>
  <p>I tried both solutions and they all have a TLE(Time Limit Exceeded). any help on how to optimize it?
  Link to question: <a href="https://www.hackerrank.com/challenges/maximum-element/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/maximum-element/problem</a></p>