The Wayback Machine - https://web.archive.org/web/20220116163159/https://www.geeksforgeeks.org/minimize-difference-with-0-after-adding-or-subtracting-any-element-of-the-given-array/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize difference with 0 after adding or subtracting any element of the given Array

  • Last Updated : 16 Jan, 2022

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 difference
long 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 code
int main()
{
    int arr[] = { 1, 2, 1, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << minDist(arr, 0, N, 0);
    return 0;
}
Output
1

Time Complexity: O(2N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!