Advertisement
HXXXXJ

84. Largest Rectangle in Histogram

Apr 14th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.88 KB | None | 0 0
  1.     func largestRectangleArea(_ hei: [Int]) -> Int {
  2.         var heights = hei
  3.         heights.append(0)
  4.         var res = 0
  5.         var stackH = [Int]()
  6.         var stackIndex = [Int]()
  7.         //保持递增
  8.         for (index, h) in heights.enumerated(){
  9.             if stackH.count  == 0 || h > stackH.last! {
  10.                 stackH.append(h)
  11.                 stackIndex.append(index)
  12.             }else {
  13.                 while stackH.count > 0 && h <= stackH.last! {
  14.                     let lastH = stackH.removeLast()
  15.                     stackIndex.removeLast()
  16.                     let leftIndex = stackIndex.count > 0 ? stackIndex.last! : -1
  17.                     res = max(res, lastH * (index - leftIndex - 1))
  18.                 }
  19.                 stackH.append(h)
  20.                 stackIndex.append(index)
  21.             }
  22.            
  23.         }
  24.         return res
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement