Minimize difference with 0 after adding or subtracting any element of the given Array
Given an array arr[] of N integers, the task is to find the minimum difference from 0 after adding or subtracting any element of the array from it.
Examples:
Input: N = 4, arr[] = {1, 2, 1, 3}
Output: 1
Explanation: Add 1 and 2 with 0 and subtract 1 and 3.
So total sum = (1 + 2 – 1 – 3) = -1. Difference is 1.Input: N = 3, arr[] = {3, 3, 3}
Output: 3
Explanation: No matter which order is chosen, the minimum possible difference is 3.Input: N = 1, arr[] = {100}
Output: 100
Explanation: There is only one element so difference will be 100
Approach: The problem focusses on forming an Exponential Recursive Tree where there are two possibilities each time. One to add element and one to subtract it. Follow the given steps:
- Create a recursive function minDist having arguments original array arr, iterating index r starting from 0, length of the array N, and integer to calculate current distance k.
- If r becomes equal to n means all elements are traversed so return current distance k.
- Else return minimum of minDist(arr, r+1, N, k+arr[r]) and minDist(arr, r+1, N, k-arr[r]).
Below is the implementation of the above approach.
C++14
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum differencelong long minDist(int* arr, int r, int N, long long k){ if (r == N) return k; else return min(abs(minDist(arr, r + 1, N, k + arr[r])), abs(minDist(arr, r + 1, N, k - arr[r])));} // Driver codeint main(){ int arr[] = { 1, 2, 1, 3 }; int N = sizeof(arr) / sizeof(arr[0]); cout << minDist(arr, 0, N, 0); return 0;} |
1
Time Complexity: O(2N)
Auxiliary Space: O(1)


