Maximizing Area in a Bar Graph

Given an array of n integers, where each integer represents the height of a bar in a bar graph, write a function that returns the maximum area that can be formed by choosing two bars from the array and stacking them on top of each other.

Problem

You are given an array of n integers, where each integer represents the height of a bar in a bar graph. Write a function that returns the maximum area that can be formed by choosing two bars from the array and stacking them on top of each other.
For example, given the array [2,1,5,6,2,3], the maximum area that can be formed is 10 (by choosing bars 2 and 3 and stacking them on top of each other).
Input:
An array of n integers, where each integer represents the height of a bar in a bar graph.
Output:
The maximum area that can be formed by choosing two bars from the array and stacking them on top of each other.

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxArea(vector<int>& height) {
    int maxArea = 0;
    int left = 0;
    int right = height.size() - 1;
    while (left < right) {
        maxArea = max(maxArea, min(height[left], height[right]) * (right - left));
        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }
    return maxArea;
}

int main() {
    vector<int> height = {2,1,5,6,2,3};
    cout << maxArea(height) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The approach is to keep track of the maximum area while iterating through the array from both sides.

Evaluated at: 2022-12-13 00:15:37