通过生成一个大小为 N 且总和为 X 的数组可能的最大中位数
给定两个正整数N和X 。任务是通过生成一个大小为N且总和为X的数组来打印可能的最大中位数
例子:
Input: N = 1, X = 7
Output: 7
Explanation: Array can be: [7], median is the 1st element, i.e., 7.
Input: N = 7, X = 18
Output: 4
Explanation: One of the possible arrays can be: [0, 1, 2, 3, 4, 4, 4]. The median = ceil(n/2)th element = ceil(7/2) = 5th element, i.e., 4.
方法:考虑中值需要最大化,因此贪心方法可以是使中值元素位置之前的所有元素为零,并将总和X等分到其余元素中。
请按照以下步骤解决问题:
- 如果n = 1 ,则打印X 。
- 对于n >= 2。
- 创建一个变量median_pos = ceil((double)(n)/2.0)。
- 递减median_pos ,以表示索引值。
- 创建一个变量median = X/(n-median_pos) 。
- 打印中位数。
以下是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the maximum median possible
int maximizeMedian(int n, int X)
{
// If only 1 element present
if (n == 1) {
return X;
}
else {
// Position of median
int median_pos = ceil((double)(n) / (2.0));
median_pos--;
int median = X / (n - median_pos);
return median;
}
return 0;
}
// Driver Code
int main()
{
int n = 1, X = 7;
cout << maximizeMedian(n, X);
}
Java
// Java program for the above approach
import java.util.*;
public class GFG
{
// Function to find the maximum median possible
static int maximizeMedian(int n, int X)
{
// If only 1 element present
if (n == 1) {
return X;
}
else {
// Position of median
int median_pos
= (int)Math.ceil((double)(n) / (2.0));
median_pos--;
int median = X / (n - median_pos);
return median;
}
}
// Driver Code
public static void main(String args[])
{
int n = 1, X = 7;
System.out.println(maximizeMedian(n, X));
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code for the above approach
# Function to find the maximum median possible
def maximizeMedian(n, X):
# If only 1 element present
if (n == 1):
return X
else:
# Position of median
median_pos = (n) // (2.0)
median_pos -= 1
median = X // (n - median_pos)
return median
return 0
# Driver Code
n = 1
X = 7
print(maximizeMedian(n, X))
# This code is contributed by gfgking
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the maximum median possible
static int maximizeMedian(int n, int X)
{
// If only 1 element present
if (n == 1) {
return X;
}
else {
// Position of median
int median_pos
= (int)Math.Ceiling((double)(n) / (2.0));
median_pos--;
int median = X / (n - median_pos);
return median;
}
}
// Driver Code
public static void Main()
{
int n = 1, X = 7;
Console.WriteLine(maximizeMedian(n, X));
}
}
// This code is contributed by ukasp.
Javascript
输出
7
时间复杂度: O(1)
辅助空间: O(1)