Categories
interview

Largest Rectangular Area in a Histogram

/**
 * @param {number[]} inp
 * @return {number}
 */
const largestRectangleArea = function(inp) {
  const s = [];
  let i = 0;
  let max = 0;
  while (i < inp.length) {
    const val = inp[i];
    if (!s.length || val >= inp[s[s.length - 1]]) {
      s.push(i++);
    } else {
      const top = s.pop();
      max = Math.max(s.length ? (i - s[s.length - 1] - 1) * inp[top] : i * inp[top], max);
    }
  }
  while (s.length) {
    const top = s.pop();
    max = Math.max(s.length ? (i - s[s.length - 1] - 1) * inp[top] : i * inp[top], max);
  }
  return max;
};

Demo