📜  给定周长的最大矩形面积

📅  最后修改于: 2021-10-23 09:05:12             🧑  作者: Mango

给定矩形的周长,任务是找到可以使用 n 单位长度作为周长的矩形的最大面积。

注意:长度和宽度必须是整数值。

例子:

Input: perimeter = 15
Output: Maximum Area = 12

Input: perimeter = 16
Output: Maximum Area = 16

方法:要使任何矩形的面积最大,长度和宽度的差异必须最小。因此,在这种情况下,长度必须是 ceil(周长 / 4),而宽度必须是地板(周长 /4)。因此,给定周长的矩形的最大面积等于ceil(perimeter/4) * floor(perimeter/4)

下面是上述方法的实现:

C++
// C++ to find maximum area rectangle
#include 
using namespace std;
 
// Function to find max area
int maxArea(float perimeter)
{
    int length = (int)ceil(perimeter / 4);
    int breadth = (int)floor(perimeter / 4);
 
    // return area
    return length * breadth;
}
 
// Driver code
int main()
{
    float n = 38;
    cout << "Maximum Area = " << maxArea(n);
 
    return 0;
}


Java
//Java to find maximum area rectangle
 
import java.io.*;
 
class GFG {
// Function to find max area
static int maxArea(float perimeter)
{
    int length = (int)Math.ceil(perimeter / 4);
    int breadth = (int)Math.floor(perimeter / 4);
 
// return area
return length * breadth;
}
 
// Driver code
     
    public static void main (String[] args) {
 
        float n = 38;
        System.out.println("Maximum Area = " +
                maxArea(n));
         
    }
}


Python3
# Python3 program to find
# maximum area rectangle
from math import ceil, floor
 
# Function to find max area
def maxArea(perimeter):
    length = int(ceil(perimeter / 4))
    breadth = int(floor(perimeter / 4))
 
    # return area
    return length * breadth
 
# Driver code
if __name__ == '__main__':
    n = 38
    print("Maximum Area =", maxArea(n))


C#
// C# to find maximum area rectangle
using System;
 
class GFG
{
// Function to find max area
static int maxArea(float perimeter)
{
    int length = (int)Math.Ceiling(perimeter / 4);
    int breadth = (int)Math.Floor(perimeter / 4);
 
    // return area
    return length * breadth;
}
 
// Driver code
public static void Main()
{
    float n = 38;
    Console.WriteLine("Maximum Area = " +
                             maxArea(n));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


PHP


Javascript


输出:
Maximum Area = 90

时间复杂度: O(1)
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程