LeetCode Problem: 11. Container With Most Water

Problem description can be found here.
What we need to do:

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

A trivial solution that comes into mind is Brute Force approach. what we can do is find area for all the possible lines drawn on the x-axis.
Time Comlexity of this solution is O(n^2) which will get a Time Limit Exceeded.

Next Possible appoach is a Two Pointer Approach. We know that further the line more area will be obtained and area is limited by the shortest of both lines. In this Approach we will start from further most points. ie 0 and n-1. We move our pointers by deciding using legth of two lines. We will move min(lo, hi) inwards ie the line which is shorter out of these two will be moved one unit towards the center. And we calucate area at each point until we reach the condition where lo >= hi. So at this point we have our answer.

Here is the solution in scala.

object Solution {
  def maxArea(height: Array[Int]): Int = {
    def solve(lo: Int, hi: Int, res: Int): Int = {
      if (lo >= hi) res
      else if (height(lo) < height(hi))
        solve(lo + 1, hi, res max ((hi - lo) * (height(lo) min height(hi))))
      else solve(lo, hi - 1, res max ((hi - lo) * (height(lo) min height(hi))))
    }
    solve(0, height.size - 1, Int.MinValue)
  }
}

Time Comlexity of this solution is : O(n)
Inspite of being recursive, space complexity of this solution is: O(1) because this method is tail call optimized by the scala compiler.