Number of different positions where a person can stand
Last Updated :
21 Aug, 2022
A person stands in the line of n people, but he doesn’t know exactly which position he occupies. He can say that there are no less than ‘f’ people standing in front of him and no more than ‘b’ people standing behind him. The task is to find the number of different positions he can occupy.
Examples:
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.
Approach: Let us iterate through each item and check whether it is appropriate to the conditions a<=i-1 and n-i<=b (for i from 1 to n). The first condition can be converted into a+1<=i, and the condition n-i<=b in n-b<=i, then the general condition can be written max(a+1, n-b)<=i and then our answer can be calculated by the formula n-max(a+1, n-b)+1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findPosition( int n, int f, int b)
{
return n - max(f + 1, n - b) + 1;
}
int main()
{
int n = 5, f = 2, b = 3;
cout << findPosition(n, f, b);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
static int findPosition( int n, int f, int b)
{
return n - Math.max(f + 1 , n - b) + 1 ;
}
public static void main(String args[])
{
int n = 5 , f = 2 , b = 3 ;
System.out.print(findPosition(n, f, b));
}
}
|
Python3
def findPosition(n, f, b):
return n - max (f + 1 , n - b) + 1 ;
n, f, b = 5 , 2 , 3
print (findPosition(n, f, b))
|
C#
using System;
class GFG
{
static int findPosition( int n,
int f, int b)
{
return n - Math.Max(f + 1, n - b) + 1;
}
public static void Main()
{
int n = 5, f = 2, b = 3;
Console.WriteLine(findPosition(n, f, b));
}
}
|
PHP
<?php
function findPosition( $n , $f , $b )
{
return $n - max( $f + 1,
$n - $b ) + 1;
}
$n = 5; $f = 2; $b = 3;
echo findPosition( $n , $f , $b );
?>
|
Javascript
<script>
function findPosition(n,f,b)
{
return n - Math.max(f + 1, n - b) + 1;
}
let n = 5, f = 2, b = 3;
document.write(findPosition(n, f, b));
</script>
|
Time Complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...