Okay so to do this, you just need to find the least common multiple of 45 and 39(because 45 - 9 = 39)
The reason you are finding the least common multiple is because the total number of sweets does not change and you know that it is divisible by both 45 and 39 because the pupils share them equally.
To find the LCM of 45 and 39, multiply 45 by 39 and divide that by the greatest common factor which is 3
LCM = 1755 / 3 = 585
Therefore your answer is 585 sweets
To check this, if you do 585 / 45 you get 13 sweets (each person gets 13 sweets originally)
After 9 people gave all their sweets away, only 39 people have sweets left so you do 585 / 39 = 15 (each person gets 15 sweets after 9 pupils gave them away to the rest)