There are 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[] = { 3, 2, 7, 4, 1 };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 sumcal, long 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 sumcal, long long sum){if (i == 0)return abs((sum - sumcal) - sumcal);return min(appleDivision(arr, i - 1,sumcal + arr[i - 1], sum),appleDivision(arr, i - 1, sumcal, sum));}int main(){long long n = 5;long long arr[n] = {3, 2, 7, 4, 1};long long sum = 0;for (long long i = 0; i < n; i++)sum += arr[i];cout << appleDivision(arr, n, 0, sum) << "\n";return 0;}
No comments:
Post a Comment