How do I find the closest possible sum of an Array's elements to a particular value?

后端 未结 4 698
青春惊慌失措
青春惊慌失措 2021-01-02 07:31

In Java, how should I find the closest (or equal) possible sum of an Array\'s elements to a particular value K?

For example, for the array {19,23,41,5,40,36} and K=4

4条回答
  •  遥遥无期
    2021-01-02 07:41

    private int closestSum(int[] a, int num){
        int k=a.length-1;
        int sum=0;
        Arrays.sort(a);
    
        while(a[k]>num){
            k--;
        }
        for(int i=0;isum)
                    sum = a[i]+a[j];
            }
        }
        return sum;
    }
    

提交回复
热议问题