DSA Day 3/100

DSA Day 3/100

Topic: Array

Questions Attempted: 1

1

Sum Pair closest to X

int[] sumClosest(int[] arr, int x) {
        if(arr.length==2){
            return arr;
        }
        int[] arr2 = new int[arr.length];
        int prevSum=x;
        int newSum=0;
        int pair1element = 0;
        int pair2element = 0;
        for(int i=0;i<arr.length-1;i++){
            for(int j=i+1;j<arr.length;j++){
                newSum = x - (arr[i]+arr[j]);
                if(prevSum>=newSum && newSum>0){
                    if(newSum==0){
                        pair1element=arr[i];
                        pair2element=arr[j];
                        break;
                    }
                    else{
                    prevSum=newSum;
                    pair1element=arr[i];
                    pair2element=arr[j];
                    }
                }
            }
        }
        arr2[0]=pair1element;
        arr2[1]=pair2element;
        return arr2;
    }

Thankyou for Reading :)