Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
classSolution{ publicintlargestRectangleArea(int[] heights){ int max = 0, n = heights.length; for ( int i = 0; i < n; i++ ) { int left = i - 1, right = i + 1; while ( left >= 0 && heights[left] >= heights[i] ) left--; while ( right < n && heights[right] >= heights[i] ) right++; int area = (right - left - 1) * heights[i]; if ( max < area ) max = area; } return max; } }
privateintlargestRectangleArea(int[] heights){ if ( matrix == null || matrix.length == 0 ) return0; int max = 0, n = heights.length; int[] small_left = newint[n]; int[] small_right = newint[n]; small_left[0] = -1; small_right[n-1] = n; for ( int i = 1; i < n; i++ ) { int idx = i - 1; while ( idx >= 0 && heights[idx] >= heights[i] ) idx = small_left[idx]; small_left[i] = idx; } for ( int i = n - 2; i >= 0; i-- ) { int idx = i + 1; while ( idx < n && heights[idx] >= heights[i] ) idx = small_right[idx]; small_right[i] = idx; } for ( int i = 0; i < n; i++ ) { int area = (small_right[i] - small_left[i] - 1) * heights[i]; if ( area > max ) max = area; } return max; }