C++ Program to get maximum area of rectangle made from line segments

Suppose we have an array A with four lines. Amal wants to draw four line segments on a sheet of paper. The i-th segment to have its length equal to A[i]. These segments can intersect with each other, and each segment should be either horizontal or vertical. Amal wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be as maximum as possible. We have to find the possible area value.

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.

https://www.tutorialspoint.com/data_structures_algorithms/greedy_algorithms.htm

https://www.tutorialspoint.com/data_structures_algorithms/dynamic_programming.htm

So, if the input of our problem is like A = [3, 1, 4, 1], then the output will be 3, because there will be a rectangle with side 3, 1, 1, 3, so the area is 3 * 1 = 3.

Steps

To solve this, we will follow these steps −

sort the array A
return A[0] * A[2]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
sort(A.begin(), A.end());
return A[0] * A[2];
}
int main(){
vector<int> A = { 3, 1, 4, 1 };
cout << solve(A) << endl;
}

Input

{ 3, 1, 4, 1 }

Output

3