Apple Division

There are n apples with known weights. Your task is to divide the apples into two groups so that the difference between the weights of the groups is minimal.

Example:

Input:  n = 5, arr = {3, 2, 7, 4, 1}
Output: 1

Approach

Java

public class AppleDivision {
    public static void main(String[] args) {

        long n = 5;

        long arr[] = { 32741 };
        long sum = 0;

        for (long i = 0; i < n; i++)
            sum += arr[(int) i];
        System.out.println(appleDivision(arr, n, 0, sum));

    }

    static long appleDivision(long arr[], long i
long sumcallong sum) {
        if (i == 0)
            return Math.abs((sum - sumcal) - sumcal);
        return Math.min(appleDivision(arr, i - 1,
 sumcal + arr[(int) (i - 1)], sum),
                appleDivision(arr, i - 1, sumcal, sum));
    }

}

C++

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

long long appleDivision(long long arr[], long long i,
                        long long sumcallong long sum)
{
    if (i == 0)
        return abs((sum - sumcal) - sumcal);
    return min(appleDivision(arri - 1
sumcal + arr[i - 1], sum),
               appleDivision(arri - 1sumcalsum));
}
int main()
{
    long long n = 5;

    long long arr[n] = {32741};
    long long sum = 0;

    for (long long  i = 0i < ni++)
        sum += arr[i];
    cout << appleDivision(arrn0sum<< "\n";
    return 0;
}


No comments:

Post a Comment