Help me in solving KCLOSE problem

My issue

Can anyone tell what is wrong in the code, it is passing all the test cases that are visible but the hidden one are failing

My code

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
	int n;
	cin >> n;
	for (int i=0; i<n; i++){
	    int N,K;
	    cin >> N >> K;
	    vector<int> arr(N);
	    for (int j=0; j<N; j++){
	        cin >> arr[j];
	    }
	    // to find maximum number in array
	    int maxi = arr[0];
	    for (int j=1; j<N; j++){
	        maxi = max(maxi, arr[j]);
	    }
	    
	    for (int j=0; j<N; j++){
	        while (maxi-arr[j] > K/2){
	            arr[j]+=K;
	        }
	    }
	    
	    // to find minimum and the new maximum number
	    int mini = arr[0];
	    int max_num = 0;
	    for (int j=1; j<N; j++){
	        mini = min(mini, arr[j]);
	        max_num = max(max_num, arr[j]);
	    }

        // printing the difference
	    cout << max_num-mini << endl;
	}
}

Problem Link: K-Closeness Practice Coding Problem - CodeChef

In the last for loop, max_num is initialised to 0. You then iterate j over 1 to N-1. This means max_num will store the largest element in the array except the first element. i.e. if the array at this stage is [5, 2, 4] then max_num will have the value 4 after this loop.

Even if you fix this by iterating j from 0 to N-1, the logic is wrong so this approach will not work.
Consider the test case A = [1, 2, 4] with K=4. Based on this approach, the ideal array should be [5, 2, 4] with difference = 3 but this is not optimal. The optimal array is [5, 6, 4] with difference = 2.

Ok, got it
But Now I have changed the code to this and it is still not working (can’t satisfy hidden test cases).

My Code

include <bits/stdc++.h>
using namespace std;

int main() {
// your code goes here
int n;
cin >> n;
for (int i=0; i<n; i++){
int N,K;
cin >> N >> K;
vector arr(N);
for (int j=0; j<N; j++){
cin >> arr[j];
}
// to find maximum number in array
int maxi = *max_element(arr.begin(), arr.end());

    for (int j=0; j<N; j++){
        while (maxi-arr[j] > K/2){
            arr[j]+=K;
        }
    }
    
    // to find minimum and the new maximum number
    int min_num = *min_element(arr.begin(), arr.end());
    int max_num = *max_element(arr.begin(), arr.end());

    // printing the difference
    cout << max_num-min_num << endl;
}

}

Can you help in finding the error, I have provided the further error above