Wrong answer despite passing the test cases, please help

Below is my code for problem with problem code : BUYING2, link: https://www.codechef.com/problems/BUYING2
it is giving me “wrong answer” on submission, while it is running smoothly on my pc, please help me out, I am new around here…

import java.util.Scanner;
class BUYING2 {

public static void main(String args[]) {
	Scanner in = new Scanner(System.in);
	int T = in.nextInt();
	while(T > 0) {
		int Total = 0;
		boolean flag = false;
		int N = in.nextInt();
		int X = in.nextInt();
		int A[] = new int[N];
		for(int i = 0; i < N; i++) {
			A[i] = in.nextInt();
			Total = Total + A[i];
		}
		int noOfSweets = Total / X;
		for(int i = 0; i < N; i++) {
			if((Total % X) - A[i] > 0) {
				flag = true;
				break;
			}
		}
		if(flag == true)
			System.out.println("-1");
		else
			System.out.println(noOfSweets);
		T--;
	}
	in.close();
}

}

Let’s consider the input
N=2, X=10
A=[20, 2]

In this case, your program would still say 2 as he can buy 2 sweets.

When you do

if ( (Total % X) - A[i] > 0)

it misses the condition where there might be a banknote of the same denomination as the extra amount. Modify it to >= instead of just > and it will run fine.

if ( (Total % X) - A[i] >= 0)

To reduce the confusion, might I suggest a simpler approach:

if ( total - A[i] >= noOfSweets * X)
    flag = true;  

i.e if after throwing away a note, the amount left is greater than or equal to the cost required to buy noOfSweets sweets, set flag = true

Hope it helped.

Yes yes it helped a lot! now I see what I was missing, tonight I can sleep peacefully, and thank you so much for the help captain.