|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function histogramArea(arr) read the |
| 3 | + * array of non-negative integers stored in arr which will represent the heights |
| 4 | + * of bars on a graph (where each bar width is 1), and determine the largest |
| 5 | + * area underneath the entire bar graph. For example: if arr is [2, 1, 3, 4, 1] |
| 6 | + * then this looks like the following bar graph: |
| 7 | + * |
| 8 | + * [Image of Example Histogram](https://i.imgur.com/GyUx5Gh.jpg) |
| 9 | + * |
| 10 | + * You can see in the above bar graph that the largest area underneath the graph |
| 11 | + * is covered by the x's. The area of that space is equal to 6 because the |
| 12 | + * entire width is 2 and the maximum height is 3, therefore 2 * 3 = 6. Your |
| 13 | + * program should return 6. The array will always contain at least 1 element. |
| 14 | + * |
| 15 | + * https://www.coderbyte.com/results/bhanson:Histogram%20Area:JavaScript |
| 16 | + * |
| 17 | + * @param {array} arr |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +function histogramArea(arr) { |
| 21 | + const histogram = arr; |
| 22 | + |
| 23 | + // Generate combos |
| 24 | + const combos = []; |
| 25 | + for (let max = Math.pow(2, histogram.length), i = 0; i < max; i++) { |
| 26 | + let combo = i.toString(2); |
| 27 | + // Pad left |
| 28 | + while (combo.length < histogram.length) { |
| 29 | + combo = '0' + combo; |
| 30 | + } |
| 31 | + |
| 32 | + // 1s must be adjacent with no 0s in between |
| 33 | + const goodComboRegEx = /^[0]*[1]+[0]*$/; |
| 34 | + const goodCombo = goodComboRegEx.test(combo); |
| 35 | + if (goodCombo) { |
| 36 | + combos.push(combo); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + let maxArea = 0; |
| 41 | + combos.forEach(combo => { |
| 42 | + const area = histogramAreaOfCombo(histogram, combo); |
| 43 | + if (area > maxArea) { |
| 44 | + maxArea = area; |
| 45 | + } |
| 46 | + }); |
| 47 | + |
| 48 | + return maxArea; |
| 49 | +} |
| 50 | + |
| 51 | +function histogramAreaOfCombo(histogram, combo) { |
| 52 | + const hist = histogram.filter((element, index) => combo[index] === '1'); |
| 53 | + const maxHeight = Math.min(...hist); |
| 54 | + return maxHeight * hist.length; |
| 55 | +} |
| 56 | + |
| 57 | +module.exports = histogramArea; |
0 commit comments