Better solution for Q17_21_Volume_of_Histogram
Author: jyothiasapuCreated Nov 23, 2017Updated Jan 22, 2025
Gayle, Can you please check below solution with O(n) time complexity and O(1) space.
public static int computeVolume(int[] arr) {
MaxElemAndPos mp = getMax(arr);
int sum = 0;
int curMax = 0;
// Calculate volume till the max.
for (int i = 0; i < mp.elemPos; i++) {
if (arr[i] > curMax) {
curMax = arr[i];
}
sum += (curMax - arr[i]);
}
curMax = 0;
for (int i = arr.length - 1; i > mp.elemPos; i--) {
if (arr[i] > curMax) {
curMax = arr[i];
}
sum += (curMax - arr[i]);
}
return sum;
}
private static MaxElemAndPos getMax(int[] arr) {
MaxElemAndPos mp = new MaxElemAndPos();
mp.elemPos = 0;
mp.maxElem = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > mp.maxElem) {
mp.maxElem = arr[i];
mp.elemPos = i;
}
}
return mp;
}
public static class MaxElemAndPos {
int maxElem;
int elemPos;
}Source: careercup/CtCI-6th-Edition