📌  相关文章
📜  添加或减去给定数组的任何元素后,用 0 最小化差异

📅  最后修改于: 2022-05-13 01:56:05.907000             🧑  作者: Mango

添加或减去给定数组的任何元素后,用 0 最小化差异

给定一个包含N个整数的数组arr[] ,任务是在添加或减去该数组的任何元素后找到与 0 的最小差。

例子:

方法:问题集中在形成一个每次有两种可能性的指数递归树。一个加元素,一个减元素。按照给定的步骤:

  • 创建一个递归函数minDist ,其参数为原始数组arr 、从 0 开始的迭代索引r 数组的长度N和整数以计算当前距离k
  • 如果r等于n意味着遍历所有元素,因此返回当前距离k
  • 否则返回minDist(arr, r+1, N, k+arr[r])minDist(arr, r+1, N, k-arr[r]) 的最小值

下面是上述方法的实现。

C++
// C++ code to implement above approach
#include 
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;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
  // Function to find the minimum difference
  static long minDist(int arr[ ], int r, int N, long k)
  {
    if (r == N)
      return k;
    else
      return Math.min(Math.abs(minDist(arr, r + 1, N, k + arr[r])), Math.abs(minDist(arr, r + 1, N, k - arr[r])));
  }
 
  public static void main (String[] args)
  {
    int arr[] = { 1, 2, 1, 3 };
    int N = arr.length;
    System.out.print(minDist(arr, 0, N, 0));
  }
}
 
// This code is contributed by hrithikgarg03188


Python3
# Python code to implement above approach
 
# Function to find the minimum difference
def minDist(arr, r, N, 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
arr = [1, 2, 1, 3]
N = len(arr)
print(minDist(arr, 0, N, 0))
 
# This code is contributed by gfgking


C#
// C# program for the above approach
using System;
class GFG {
 
    // Function to find the minimum difference
    static long minDist(int[] arr, int r, int N, long k)
    {
        if (r == N)
            return k;
        else
            return Math.Min(Math.Abs(minDist(arr, r + 1, N,
                                             k + arr[r])),
                            Math.Abs(minDist(arr, r + 1, N,
                                             k - arr[r])));
    }
 
    public static void Main()
    {
        int[] arr = { 1, 2, 1, 3 };
        int N = arr.Length;
        Console.Write(minDist(arr, 0, N, 0));
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
1

时间复杂度: O(2 N )
辅助空间: O(1)