Skip to content

Make tailrec to avoid stack overflow issue? #21

@zhaomingli007

Description

@zhaomingli007

def maxRectangleInHistogram(heights: List[Int]): Int = {

def maxRectangleInHistogram(heights: List[Int]): Int = {
    @tailrec def solve(stack: List[(Int, Int)], remaining: List[(Int, Int)],maxArea:Int): Int = {
      def area(x: Int, y: Int) = (heights.length - remaining.length - x) * y
      (stack, remaining) match {
        case (           Nil,          Nil)           => maxArea
        case ((y, x) :: rest,          Nil)           => solve(          rest,          Nil, maxArea max area(x, y)) 
        case ((y, x) :: rest, (h, i) :: hs) if h <= y => solve(          rest, (h, x) :: hs, maxArea max area(x, y)) 
        case (             _,  block :: hs)           => solve(block :: stack,           hs, maxArea)
      }
    }
    solve(Nil, heights.zipWithIndex,0)
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions