Finding Shoes---Difficulty: 646---Python Solution

Finding Shoes
Difficulty: 646

Chef has N friends. Chef promised that he would gift a pair of shoes (consisting of one left shoe and one right shoe) to each of his N friends. Chef was about to go to the marketplace to buy shoes, but he suddenly remembers that he already had M left shoes.

What is the minimum number of extra shoes that Chef will have to buy to ensure that he is able to gift a pair of shoes to each of his N friends?

For example, if
N = 2, M=4, then Chef already has 4 left shoes, so he must buy 2 extra right shoes to form 2 pairs of shoes.

Therefore Chef must buy at least 2 extra shoes to ensure that he is able to get
N=2 pairs of shoes.

Input Format
The first line contains a single integer
T - the number of test cases. Then the test cases follow.
The first line of each test case contains two integers
N and M - the number of Chef’s friends and the number of left shoes Chef has.
Output Format
For each test case, output the minimum number of extra shoes that Chef will have to buy to ensure that he is able to get
N pairs of shoes.

Solution

t = int(input())
for _ in range(t):
n,m = map(int, input().split())
left_shoes = max(0, n-m)
right_shoes = n
total_shoes = left_shoes + right_shoes
print(total_shoes)

Explanation

  • Input Parsing:
  • You read the number of test cases t using t = int(input()).
  • Then for each test case, you read the values of n (number of friends/pairs of shoes needed) and m (number of left shoes Chef already has) using n, m = map(int, input().split()).
  • Logic to Calculate Extra Shoes:
  • You calculate the number of extra left shoes Chef needs: left_shoes = max(0, n - m). This ensures Chef only buys extra left shoes if he has fewer than n.
  • Chef will always need n right shoes, which you store as right_shoes = n.
  • The total number of extra shoes Chef needs to buy is total_shoes = left_shoes + right_shoes.
  • Output:
  • For each test case, you print the result using print(total_shoes).

Test Case 1:

  • Chef needs 2 pairs of shoes (2 left and 2 right).
  • Chef already has 4 left shoes, so he doesn’t need any more left shoes.
  • Chef needs 2 right shoes.
  • Output: 2 extra shoes.

Test Case 2:

  • Chef needs 6 pairs of shoes (6 left and 6 right).
  • Chef has no left shoes, so he needs to buy 6 left shoes.
  • Chef also needs 6 right shoes.
  • Output: 12 extra shoes.

Test Case 3:

  • Chef needs 4 pairs of shoes (4 left and 4 right).
  • Chef has 3 left shoes, so he needs 1 more left shoe.
  • Chef needs 4 right shoes.
  • Output: 5 extra shoes.