📜  一个人可以站立的不同位置的数量

📅  最后修改于: 2021-04-24 18:41:55             🧑  作者: Mango

一个人排成n人,但他不知道自己所处的位置。他可以说站在他前面的人不少于“ f”个人,而站在他后面的人不多于“ b”个人。任务是找到他可以担任的不同职位的数量。

例子:

Input: n = 3, f = 1, b = 1 
Output: 2
3 is the number of people in the line and there can be no less than 1 people standing in front of him and no more than 1 people standing behind him.So the positions could be 2 and 3(if we number the positions starting with 1).

Input: n = 5, f = 2, b = 3
Output: 3
In this example the positions are 3, 4, 5.

方法:让我们遍历每个项目,并检查是否适合条件a <= i-1和ni <= b(对于i从1到n)。第一个条件可以转换为a + 1 <= i ,并且条件ni <= bnb <= i中,然后一般条件可以写成max(a + 1,nb)<= i ,然后我们的答案可以由公式n-max(a + 1,nb)+1计算

下面是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
  
// Function to find the position
int findPosition(int n, int f, int b)
{
  
    return n - max(f + 1, n - b) + 1;
}
  
// Driver code
int main()
{
  
    int n = 5, f = 2, b = 3;
    cout << findPosition(n, f, b);
  
  return 0;
}


Java
// Java implementation of above approach
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG{
      
  
// Function to find the position
static int findPosition(int n, int f, int b)
{
  
    return n - Math.max(f + 1, n - b) + 1;
}
  
// Driver code
public static void main(String args[])
{
  
    int n = 5, f = 2, b = 3;
    System.out.print(findPosition(n, f, b));
  
}
}


Python3
# Python3 implementation of 
# above approach
  
# Function to find the position
def findPosition(n, f, b):
  
    return n - max(f + 1, n - b) + 1;
  
# Driver code
n, f, b = 5, 2, 3
print(findPosition(n, f, b))
  
# This code is contributed by
# Sanjit_Prasad


C#
// C# implementation of above approach
using System;
class GFG
{
      
// Function to find the position
static int findPosition(int n, 
                        int f, int b)
{
  
    return n - Math.Max(f + 1, n - b) + 1;
}
  
// Driver code
public static void Main()
{
    int n = 5, f = 2, b = 3;
    Console.WriteLine(findPosition(n, f, b));
}
}
  
// This code is contributed
// by inder_verma


PHP


输出:
3