Largest Rectangle
Difficulty: ⚫◯◯◯
Tags: array, struct, search, max
Hurdle: Passing this question is sufficient to pass the arrays hurdle.
Description
Write a function largest_rectangle that takes a struct array with exactly size rectangles.
The function should return the index of the rectangle with the largest area.
If two or more rectangles have the same largest area, return the index of the first one.
Area of a rectangle = width × height
Data Structure
struct rectangle {
int width;
int height;
};
Examples
Example 1
{width: 3, height: 4} // index 0, area = 12
{width: 2, height: 8} // index 1, area = 16 <- largest!
{width: 5, height: 2} // index 2, area = 10
Output: 1
Explanation: Rectangle at index 1 has the largest area (16).
Example 2
{width: 5, height: 5} // index 0, area = 25 <- largest
{width: 3, height: 4} // index 1, area = 12
{width: 2, height: 6} // index 2, area = 12
Output: 0
Explanation: Rectangle at index 0 has the largest area (25).
Example 3
{width: 2, height: 3} // index 0, area = 6
{width: 4, height: 2} // index 1, area = 8
{width: 5, height: 5} // index 2, area = 25 <- largest
Output: 2
Explanation: Rectangle at index 2 has the largest area (25).
Example 4: Tie
{width: 3, height: 4} // index 0, area = 12 <- first largest
{width: 2, height: 6} // index 1, area = 12 (same, but not first)
{width: 4, height: 3} // index 2, area = 12 (same, but not first)
Output: 0
Explanation: All have area 12, so return the first one (index 0).
Example 5: Single Rectangle
{width: 7, height: 3} // index 0, area = 21
Output: 0
Explanation: Only one rectangle, return index 0.
Function Signature
int largest_rectangle(int size, struct rectangle array[MAX_SIZE]);
Constants
#define MAX_SIZE 100
Constraints
- You can assume
sizeis at least 1. - You can assume all
widthandheightvalues are positive integers. - If multiple rectangles have the same largest area, return the first (smallest index).
- Return a single integer (the index).
- Do not modify the array.
- Do not call
scanf,getchar, orfgets. - Do not call
printf. - Do not change the definition of
struct rectangle.
Hints
- Track both the maximum area found and the index where it was found.
- Use
>(not>=) when comparing areas to ensure you keep the first largest. - Calculate area as
array[i].width * array[i].height.
Testing
./largest-rectangle 3,4 2,8 5,2
1
./largest-rectangle 5,5 3,4 2,6
0
./largest-rectangle 2,3 4,2 5,5
2
./largest-rectangle 3,4 2,6 4,3
0
./largest-rectangle 7,3
0