Given an array of positive integers that represent the bars in a histogram,
find the rectangle with the largest area under the curve and above the axis.
Approach:
Let the array be A = {4, 1, 6, 3, 4, 7, 5, 2}, maxArea=0 and area=0;
Now for each A[i], traverse forward till A[j] >= A[i] (j > i). - say we found n such numbers.
Calculate the area as area = A[i] * (n).
Now for A[i], traverse backwards till A[j] <= A[i], - say we found m such numbers.
area += (A[i] * m);
if (area > maxArea) then maxArea <= area.
In the end return the maxArea.
Code output:
reactange with largest area under the curve and above the axis: 12
May I the time complexity of the above algorithm ?
ReplyDelete