dimanche 20 décembre 2020

Find smallest particle by removing them and add by their absolute difference [closed]

You have given n particles (> 0) array. You smash them two particles and genrates new particle by their absolute difference and add it to particle array. Old particles have vanished.

If particles can be samshed any way Find minimum particle can be obtained.

Constraint: 1 <= particle <= 10^4

Eg1: 
I/p: 30 27 26 10 6
O/p: 0

Explanation:
30 26 samshes gives 4. Updated array  4 27 10 6
10 6 samshes gives 4. Updated array 4 27 4
4 4 samshes gives 0. Updated array 27 0
Min particle is 0

Eg2: 
I/p: 1 2 4 8
O/p: 1

Explanation:
No matter how you smash min particle is 1


Eg3: 
I/p: 101 75 40 30
O/p: 4

Explanation:
101, 75 --> 26 then 30, 26 --> 4.

This is my Brute Force Code. I solved it by taking all pair particles and by adding new genrated particle to array. What will be its optimal solution.

int getMinParticle(int start, int end, int particles[]) {
    if (end - start == 1) {
        return abs(particles[start] - particles[end]);
    }

    int i, j, minParticle = INT_MAX, newParticle, temp;
    for (i = start; i <= end; i++) {
        for (j = start + 1; j <= end; j++) {
            swap(particles[i], particles[start]);
            swap(particles[j], particles[start + 1]);

            newParticle = abs(particles[start] - particles[start + 1]);
            if (newParticle == 0) {
                return 0;
            }
            temp = particles[start + 1];
            particles[start + 1] = newParticle;

            minParticle = min(minParticle, newParticle);
            minParticle = min(minParticle, getMinParticle(start + 1, end, particles));
            if (minParticle == 0) {
                return 0;
            }
            particles[start + 1] = temp;
            swap(particles[i], particles[start]);
            swap(particles[j], particles[start + 1]);
        }
    }

    return minParticle;
}

int findMinParticle(int particles[], int n) {
    getMinParticle(0, n - 1, particles);
}

Aucun commentaire:

Enregistrer un commentaire