I am trying to implement a divide and conquer algorithm where you are given an integer array A of size n; all numbers in A are non-negative. A represents a histogram where each bar has width 1 and the i-th bar has height A[i]. My goal is to find the area of the largest rectangle in the histogram that is completely covered by bars. Here is a picture to visualize this: Histogram Area
Here is my code:
public static int problem(int[] heights) {
return largestArea(heights, 0, heights.length-1);
}
private static int largestArea(int[] heights, int low, int high){
if(low > high) return 0;
if(low == high) return heights[low];
int minIndex = findIndexOfMinimumValue(heights, low, high);
int areaWithMin = (high-low+1) * heights[minIndex];
int areaLeft = largestArea(heights, low, minIndex-1);
int areaRight = largestArea(heights, minIndex+1, high);
return Math.max(areaWithMin, Math.max(areaLeft, areaRight));
}
private static int findIndexOfMinimumValue(int[] heights, int low, int high){
int minIndex = low;
for(int i=low; i<=high; i++)
if(heights[i] < heights[minIndex])
minIndex = i;
return minIndex;
}
However I am getting a stack overflow error from this line
int areaLeft = largestArea(heights, low, minIndex-1);