添加或减去给定数组的任何元素后,用 0 最小化差异
给定一个包含N个整数的数组arr[] ,任务是在添加或减去该数组的任何元素后找到与 0 的最小差。
例子:
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
方法:问题集中在形成一个每次有两种可能性的指数递归树。一个加元素,一个减元素。按照给定的步骤:
- 创建一个递归函数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)