samedi 30 mai 2020

c++ function to find the sum fo four minimum and four maximum elements in an array not working

I am completing a question in which i have to write a function which finds the maximum and minimum sum of four integers in the array and then displays it.

I have written the following code:

void miniMaxSum(vector<int> arr) {

        int minsum=0;
        int maxsum=0;
        int l1,l2,l3,l4;
        int s1,s2,s3,s4;
        l1=arr[0];
        s1=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l1<arr[i])
            l1=arr[i];
            if(s1>arr[i])
            s1=arr[i];
        }
        l2=arr[0];
        s2=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l2<arr[i]&&arr[i]!=l1)
            l2=arr[i];
            if(s2>arr[i]&&arr[i]!=s1)
            s2=arr[i];
        }
        l3=arr[0];
        s3=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l3<arr[i]&&arr[i]!=l2&&arr[i]!=l1)
            l3=arr[i];
            if(s3>arr[i]&&arr[i]!=s2&&arr[i]!=s1)
            s3=arr[i];
        }
        l4=arr[0];
        s4=arr[0];
        for(int i=1;i<arr.size();++i)
        {
            if(l4<arr[i]&&arr[i]!=l2&&arr[i]!=l1&&arr[i]!=l3)
            l4=arr[i];
            if(s4>arr[i]&&arr[i]!=s3&&arr[i]!=s2&&arr[i]!=s1)
            s4=arr[i];
        }
        minsum=s1+s2+s3+s4;
        maxsum=l1+l2+l3+l4;
        cout<<minsum<<" "<<maxsum;
}

this code gives the correct output for maxsum but the minsum is wrong in all the testcases. Can you please help me find the error in the code i have made... Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire