📌  相关文章
📜  翻转数组元素的最小符号以获得可能的正元素的最小和

📅  最后修改于: 2021-05-04 20:25:12             🧑  作者: Mango

给定一个正元素数组,您必须翻转其某些元素的符号,以使数组元素的结果总和应为最小非负数(尽可能接近零)。返回最小编号需要翻转其符号的元素,以使结果总和为最小非负数。请注意,所有数组元素的总和将不超过10 4
例子:

天真的方法:对于数组中每个元素A [i],0≤i

  1. A [i]的符号被翻转(-ve)。
  2. A [i]的符号未翻转(+ ve)。

因此,我们总共可以配置2 n个阵列。我们可以维持每种配置中元素的总和和翻转的数量,并跟踪最小总和(领带被最小翻转数打破)。最小总和配置中的翻转数将是答案。
时间复杂度: O(2 n ),其中n是数组中元素的数量。
高效的方法:此问题可以使用动态编程解决,并且是标准0/1背包问题的变体。不同之处在于,我们在此处有2个选择,即要么在背包中包含一项,要么将其排除在外,而在这里,这就像是翻转元素的符号或不翻转元素的符号。而不是背包问题中的包重,这里是不翻转的数组所有元素的总和(问题陈述中给出的最大值为10 4 )。
最佳子结构:令dp [i] [j]为数组的前i个元素所需的最小翻转次数,以使总和等于j。
1≤i≤n和-sum≤j≤sum,其中sum是不翻转的数组所有元素的和。

注意:由于数组元素的总和在翻转后可能为负。因此,我们不能使用2D数组进行制表,因为在dp [i] [j]中,j是总和,数组的索引不能为负。因此,我们将使用哈希表数组。数组的大小为n + 1。
重叠的子问题:就像0/1背包问题一样,这里也存在重叠的子问题。我们不需要一次又一次地评估结果,而是可以将子问题的结果存储在表中。
时间复杂度: O(n *总和)
辅助空间: O(n *和)
其中n是元素数,sum是不翻转的数组元素之和。
空间优化:如果仔细研究最佳子结构,则dp [i] [j]仅取决于dp [i – 1] [j – A [i – 1]] / dp [i – 1] [j + A [i – 1]]。因此,仅涉及2行i和i –1。因此,我们只需要2行而不是n + 1。
以下是我们需要优化空间的更改。

  1. 而不是使用size = n + 1的数组,而是声明size = 2的数组。
  2. 引入一个布尔变量(例如标记)在地图之间切换。我们可以初始化dp [0]地图并开始填充dp [1]。在下一次迭代中,dp [0]是当前地图,而dp [1]在前。通过这种方式,我们可以在两个地图之间继续切换。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the
// minimum number of elements
// whose sign must be flipped
// to get the positive
// sum of array elements as close
// to 0 as possible
int solve(int A[], int n)
{
 
    // Array of unordered_map of size=2.
    unordered_map dp[2];
 
    // boolean variable used for
    // toggling between maps
    bool flag = 1;
 
    // Calculate the sum of all
    // elements of the array
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += A[i];
 
    // Initializing first map(dp[0])
    // with INT_MAX because
    // for i=0, there are no elements
    // in the array to flip
    for (int i = -sum; i <= sum; i++)
        dp[0][i] = INT_MAX;
 
    // Base Case
    dp[0][0] = 0;
 
    for (int i = 1; i <= n; i++) {
        for (int j = -sum; j <= sum; j++) {
            dp[flag][j] = INT_MAX;
            if (j - A[i - 1] <= sum && j - A[i - 1] >= -sum)
                dp[flag][j] = dp[flag ^ 1][j - A[i - 1]];
            if (j + A[i - 1] <= sum && j + A[i - 1] >= -sum
                && dp[flag ^ 1][j + A[i - 1]] != INT_MAX)
                dp[flag][j]
                    = min(dp[flag][j],
                          dp[flag ^ 1][j + A[i - 1]] + 1);
        }
 
        // For toggling
        flag = flag ^ 1;
    }
 
    // Required sum is minimum non-negative
    // So, we iterate from i=0 to sum and find
    // the first i where dp[flag ^ 1][i] != INT_MAX
    for (int i = 0; i <= sum; i++) {
        if (dp[flag ^ 1][i] != INT_MAX)
            return dp[flag ^ 1][i];
    }
 
    // In worst case we will flip max n-1 elements
    return n - 1;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << solve(arr, n);
 
    return 0;
}


Java
// Java implementation of
// the above approach:
class GFG {
 
    // Function to return the
    // minimum number of elements
    // whose sign must be flipped
    // to get the positive
    // sum of array elements as close
    // to 0 as possible
    public static int solve(int[] A, int n)
    {
        int[][] dp = new int[2000][2000];
 
        // boolean variable used for
        // toggling between maps
        int flag = 1;
 
        // Calculate the sum of all
        // elements of the array
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += A[i];
 
        // Initializing first map(dp[0])
        // with INT_MAX because for i=0,
        // there are no elements in the
        // array to flip
        for (int i = -sum; i <= sum; i++) {
            try {
                dp[0][i] = Integer.MAX_VALUE;
            }
            catch (Exception e) {
            }
        }
 
        // Base Case
        dp[0][0] = 0;
 
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= sum; j++) {
                try {
                    dp[flag][j] = Integer.MAX_VALUE;
                    if (j - A[i - 1] <= sum
                        && j - A[i - 1] >= -sum)
                        dp[flag][j]
                            = dp[flag ^ 1][j - A[i - 1]];
                    if (j + A[i - 1] <= sum
                        && j + A[i - 1] >= -sum
                        && dp[flag ^ 1][j + A[i - 1]]
                               != Integer.MAX_VALUE)
                        dp[flag][j] = Math.min(
                            dp[flag][j],
                            dp[flag ^ 1][j + A[i - 1]] + 1);
                }
                catch (Exception e) {
                }
            }
 
            // For toggling
            flag = flag ^ 1;
        }
 
        // Required sum is minimum non-negative
        // So, we iterate from i=0 to sum and find
        // the first i where dp[flag ^ 1][i] != INT_MAX
        for (int i = 0; i <= sum; i++) {
            if (dp[flag ^ 1][i] != Integer.MAX_VALUE)
                return dp[flag ^ 1][i];
        }
 
        // In worst case we will flip max n-1 elements
        return n - 1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 10, 22, 9, 33, 21, 50, 41, 60 };
        int n = arr.length;
        System.out.println(solve(arr, n));
    }
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 implementation of the approach
 
# Function to return the minimum
# number of elements
# whose sign must be flipped
# to get the positive
# sum of array elements as close
# to 0 as possible
def solve(A, n):
 
    dp = [[0 for i in range(2000)] for i in range(2000)]
 
    # boolean variable used for
    # toggling between maps
    flag = 1
 
    # Calculate the sum of all
    # elements of the array
    sum = 0
    for i in range(n):
        sum += A[i]
 
    # Initializing first map(dp[0])
    # with INT_MAX because
    # for i=0, there are no elements
    # in the array to flip
    for i in range(-sum, sum+1):
        dp[0][i] = 10**9
 
    # Base Case
    dp[0][0] = 0
 
    for i in range(1, n+1):
        for j in range(-sum, sum+1):
            dp[flag][j] = 10**9
            if (j - A[i - 1] <= sum and j - A[i - 1] >= -sum):
                dp[flag][j] = dp[flag ^ 1][j - A[i - 1]]
            if (j + A[i - 1] <= sum
                and j + A[i - 1] >= -sum
                    and dp[flag ^ 1][j + A[i - 1]] != 10**9):
                dp[flag][j] = min(dp[flag][j],
                                  dp[flag ^ 1][j + A[i - 1]] + 1)
 
        # For toggling
        flag = flag ^ 1
 
    # Required sum is minimum non-negative
    # So, we iterate from i=0 to sum and find
    # the first i where dp[flag ^ 1][i] != INT_MAX
    for i in range(sum+1):
        if (dp[flag ^ 1][i] != 10**9):
            return dp[flag ^ 1][i]
 
    # In worst case we will flip max n-1 elements
    return n - 1
 
 
# Driver code
arr = [10, 22, 9, 33, 21, 50, 41, 60]
n = len(arr)
 
print(solve(arr, n))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach:
using System;
 
class GFG
{
 
// Function to return the minimum number
// of elements whose sign must be flipped
// to get the positive sum of array elements
// as close to 0 as possible
public static int solve(int[] A, int n)
{
    int[,] dp = new int[2000, 2000];
 
    // boolean variable used for
    // toggling between maps
    int flag = 1;
 
    // Calculate the sum of all elements
    // of the array
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += A[i];
 
    // Initializing first map(dp[0]) with
    // INT_MAX because for i=0, there are
    // no elements in the array to flip
    for (int i = -sum; i <= sum; i++)
    {
        try
        {
            dp[0, i] = int.MaxValue;
        }
        catch (Exception e){}
    }
 
    // Base Case
    dp[0, 0] = 0;
 
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j <= sum; j++)
        {
            try
            {
                dp[flag, j] = int.MaxValue;
                if (j - A[i - 1] <= sum &&
                    j - A[i - 1] >= -sum)
                    dp[flag, j] = dp[flag ^ 1,
                                     j - A[i - 1]];
                if (j + A[i - 1] <= sum &&
                    j + A[i - 1] >= -sum &&
                    dp[flag ^ 1,
                       j + A[i - 1]] != int.MaxValue)
                    dp[flag, j] = Math.Min(dp[flag, j],
                                           dp[flag ^ 1,
                                           j + A[i - 1]] + 1);
            } catch (Exception e) {}
        }
 
        // For toggling
        flag = flag ^ 1;
    }
 
    // Required sum is minimum non-negative
    // So, we iterate from i=0 to sum and find
    // the first i where dp[flag ^ 1,i] != INT_MAX
    for (int i = 0; i <= sum; i++)
    {
        if (dp[flag ^ 1, i] != int.MaxValue)
            return dp[flag ^ 1, i];
    }
     
    // In worst case we will flip
    // max n-1 elements
    return n - 1;
}
 
// Driver code
public static void Main(String[] args)
{
    int[] arr = { 10, 22, 9, 33,
                  21, 50, 41, 60 };
    int n = arr.Length;
    Console.WriteLine(solve(arr, n));
}
}
 
// This code is contributed by PrinciRaj1992


输出:
3

时间复杂度: O(n *总和)。
辅助空间: O(sum),其中n是元素个数,sum是不翻转的数组元素之和。