max Area Algorithm

The Max Area Algorithm is a mathematical technique used to find the maximum area in a given array or list of positive integers, specifically in the context of container problems. The container problem, also known as the "container with most water" problem, is a classic optimization problem that asks to find two lines in an array that together with the x-axis forms a container that can hold the most water. The max area algorithm utilizes a two-pointer approach, which significantly reduces the time complexity from a brute-force solution. In the max area algorithm, two pointers are initialized at the start and end of the array. The algorithm calculates the current area between the two pointers and keeps track of the maximum area found so far. The algorithm then moves the pointer pointing to the shorter line towards the other pointer, as moving the pointer pointing to the taller line would not increase the area. This process continues until the two pointers meet, ensuring that all possible combinations have been explored. The final maximum area value is then returned as the solution. This algorithm has a time complexity of O(n), where n is the number of elements in the array, making it an efficient solution to the container problem.
/**
 * Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
 * n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
 * Find two lines, which together with x-axis forms a container, such that the container contains the most water.
 * Note: You may not slant the container.
 */

#include <iostream>
#include <vector>
#include <limits>

int maxArea(std::vector<int>& height) {
	size_t l = 0;
	size_t r = height.size() - 1;
	int maxAr = std::numeric_limits<int>::min();
	while( l < r ) {
		int curAr = ( std::min(height[l], height[r]) * ( r - l ));
		if ( curAr > maxAr ) {
			maxAr = curAr;
		}
		if ( height[l] < height[r]) {
			l++;
		} else {
			r--;
		}
	}
	return maxAr;
}

void printVec( std::vector<int> & vec ) {
	std::cout << "Heights:";
	for( auto v : vec ) {
		std::cout << v << " ";
	}
	std::cout << std::endl;
}

int main()
{
	std::vector<int> heights{ 4, 5, 1 };
	printVec(heights);
	std::cout << "Max possible area with above heights:" << maxArea(heights) << std::endl;
	return 0;
}

LANGUAGE:

DARK MODE: