Given integer N and K, denoting the number of teams participating in a football tournament where each team plays only one match with each other team, the task is to find the maximum point difference between the winner and the runner-up (second place holder) of the tournament where the winner of a match gets K points.
Examples:
Input: N = 2, K = 4
Output: 4
Explanation: If there are 2 team A and B then either A will win or lose.
If A wins the match it scores 4 points and team B score is 0.
Hence maximum possible difference of points between the winning team and the second-placed team is 4 .
Input: N = 3, K = 4
Output: 4
Input: N = 9, K = 5
Output: 20
Approach: the problem can be solved based on the following mathematical observation:
The difference will be maximum when the winner wins all the matches it plays and all the other teams win near equal matches each. As each time is playing against others only once so the total number of matches is N * (N – 1)/2.
If the winner wins all matches (i.e., (N-1) matches that it plays) the remaining number of matches are:
(N * (N – 1))/2 – (N – 1) = (N – 1) * (N – 2) / 2.
If each team wins near equal matches, the runner-up will win ceil[ (N – 1)*(N – 2) / (2 * (N – 1)) ] = ceil[ (N – 2)/2 ]
If N is odd: The value is (N – 2 + 1)/2 = (N – 1)/2
If N is even: The value is (N – 2)/2.
Matches difference when N is odd: (N – 1) – (N – 1)/2 = (N – 1)/2. So points difference = K * ((N – 1)/2).
Matches difference when N is even: (N – 1) – (N – 2)/2 = N/2. So points difference = K * (N / 2).
Follow the steps mentioned below to implement the idea:
- Check if N is odd or even.
- If N is odd the required difference is K*((N-1)/2).
- If N is even the required difference is K*(N/2).
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int pointDiff( int N, int K)
{
if (N % 3 != 0)
return ((N - 1) / 2) * K;
return (N / 2) * K;
}
int main()
{
int N = 9, K = 5;
cout << pointDiff(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int pointDiff( int N, int K)
{
if (N % 3 != 0 )
return ((N - 1 ) / 2 ) * K;
return (N / 2 ) * K;
}
public static void main(String[] args)
{
int N = 9 , K = 5 ;
System.out.println(pointDiff(N, K));
}
}
|
Python3
def pointDiff(N, K):
if N % 3 ! = 0 :
return ((N - 1 ) / / 2 ) * K
return (N / / 2 ) * K
if __name__ = = "__main__" :
N = 9
K = 5
print (pointDiff(N, K))
|
C#
using System;
using System.Linq;
public class GFG
{
public static int pointDiff( int N, int K)
{
if (N % 3 != 0)
return ((N - 1) / 2) * K;
return (N / 2) * K;
}
public static void Main( string [] args)
{
int N = 9, K = 5;
Console.WriteLine(pointDiff(N, K));
}
}
|
Javascript
<script>
function pointDiff(N, K)
{
if (N % 3 != 0)
return Math.floor((N - 1) / 2) * K;
return Math.floor(N / 2) * K;
}
let N = 9, K = 5;
document.write(pointDiff(N, K), "</br>" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)