📌  相关文章
📜  将数组拆分为两个子数组,使其总和的差异最小

📅  最后修改于: 2021-09-03 14:49:34             🧑  作者: Mango

给定一个整数数组arr[] ,任务是将给定的数组拆分为两个子数组,使得它们和之间的差异最小。

例子:

朴素的方法:这个想法是使用前缀和后缀和数组技术。生成给定数组的前缀和数组和后缀和数组。现在,迭代数组并打印prefix_sum[i]suffix_sum[i+1]之间的最小差异,对于数组中的任何索引i ( 0 <= i <= N – 1)。
时间复杂度: O(N)
辅助空间: O(N)

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to return minimum difference
// between two subarray sums
int minDiffSubArray(int arr[], int n)
{
 
    // To store prefix sums
    int prefix_sum[n];
 
    // Generate prefix sum array
    prefix_sum[0] = arr[0];
 
    for(int i = 1; i < n; i++)
        prefix_sum[i] = prefix_sum[i - 1] +
                               arr[i];
 
    // To store suffix sums
    int suffix_sum[n];
 
    // Generate suffix sum array
    suffix_sum[n - 1] = arr[n - 1];
 
    for(int i = n - 2; i >= 0; i--)
        suffix_sum[i] = suffix_sum[i + 1] +
                               arr[i];
 
    // Stores the minimum difference
    int minDiff = INT_MAX;
 
    // Traverse the given array
    for(int i = 0; i < n - 1; i++)
    {
         
        // Calculate the difference
        int diff = abs(prefix_sum[i] -
                       suffix_sum[i + 1]);
 
        // Update minDiff
        if (diff < minDiff)
            minDiff = diff;
    }
 
    // Return minDiff
    return minDiff;
}
 
// Driver Code
int main()
{
     
    // Given array
    int arr[] = { 7, 9, 5, 10 };
 
    // Length of the array
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << minDiffSubArray(arr, n);
}
 
// This code is contributed by code_hunt


Java
// Java Program for above approach
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to return minimum difference
    // between two subarray sums
    static int minDiffSubArray(int arr[], int n)
    {
 
        // To store prefix sums
        int[] prefix_sum = new int[n];
 
        // Generate prefix sum array
        prefix_sum[0] = arr[0];
 
        for (int i = 1; i < n; i++)
            prefix_sum[i]
                = prefix_sum[i - 1] + arr[i];
 
        // To store suffix sums
        int[] suffix_sum = new int[n];
 
        // Generate suffix sum array
        suffix_sum[n - 1] = arr[n - 1];
 
        for (int i = n - 2; i >= 0; i--)
            suffix_sum[i]
                = suffix_sum[i + 1] + arr[i];
 
        // Stores the minimum difference
        int minDiff = Integer.MAX_VALUE;
 
        // Traverse the given array
        for (int i = 0; i < n - 1; i++) {
 
            // Calculate the difference
            int diff
                = Math.abs(prefix_sum[i]
                           - suffix_sum[i + 1]);
 
            // Update minDiff
            if (diff < minDiff)
                minDiff = diff;
        }
 
        // Return minDiff
        return minDiff;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array
        int[] arr = { 7, 9, 5, 10 };
 
        // Length of the array
        int n = arr.length;
 
        System.out.println(
            minDiffSubArray(arr, n));
    }
}


Python3
# Python3 program for the above approach
import sys
 
# Function to return minimum difference
# between two subarray sums
def minDiffSubArray(arr, n):
 
    # To store prefix sums
    prefix_sum = [0] * n
 
    # Generate prefix sum array
    prefix_sum[0] = arr[0]
 
    for i in range(1, n):
        prefix_sum[i] = (prefix_sum[i - 1] +
                                arr[i])
 
    # To store suffix sums
    suffix_sum = [0] * n
 
    # Generate suffix sum array
    suffix_sum[n - 1] = arr[n - 1]
 
    for i in range(n - 2, -1, -1):
        suffix_sum[i] = (suffix_sum[i + 1] +
                                arr[i])
 
    # Stores the minimum difference
    minDiff = sys.maxsize
 
    # Traverse the given array
    for i in range(n - 1):
 
        # Calculate the difference
        diff = abs(prefix_sum[i] -
                   suffix_sum[i + 1])
 
        # Update minDiff
        if (diff < minDiff):
            minDiff = diff
 
    # Return minDiff
    return minDiff
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [ 7, 9, 5, 10 ]
 
    # Length of the array
    n = len(arr)
 
    print(minDiffSubArray(arr, n))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to return minimum difference
// between two subarray sums
static int minDiffSubArray(int []arr,
                           int n)
{   
  // To store prefix sums
  int[] prefix_sum = new int[n];
 
  // Generate prefix sum array
  prefix_sum[0] = arr[0];
 
  for(int i = 1; i < n; i++)
    prefix_sum[i] = prefix_sum[i - 1] +
                    arr[i];
 
  // To store suffix sums
  int[] suffix_sum = new int[n];
 
  // Generate suffix sum array
  suffix_sum[n - 1] = arr[n - 1];
 
  for(int i = n - 2; i >= 0; i--)
    suffix_sum[i] = suffix_sum[i + 1] +
                    arr[i];
 
  // Stores the minimum difference
  int minDiff = int.MaxValue;
 
  // Traverse the given array
  for(int i = 0; i < n - 1; i++)
  {
    // Calculate the difference
    int diff = Math.Abs(prefix_sum[i] -
                        suffix_sum[i + 1]);
 
    // Update minDiff
    if (diff < minDiff)
      minDiff = diff;
    }
 
    // Return minDiff
    return minDiff;
}
 
// Driver Code
public static void Main(String[] args)
{   
    // Given array
    int[] arr = {7, 9, 5, 10};
 
    // Length of the array
    int n = arr.Length;
 
    Console.WriteLine(minDiffSubArray(arr, n));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ program for above approach
#include 
using namespace std;
 
// Function to return minimum difference
// between sum of two subarrays
int minDiffSubArray(int arr[], int n)
{
     
    // To store total sum of array
    int total_sum = 0;
 
    // Calculate the total sum
    // of the array
    for(int i = 0; i < n; i++)
        total_sum += arr[i];
 
    // Stores the prefix sum
    int prefix_sum = 0;
 
    // Stores the minimum difference
    int minDiff = INT_MAX;
 
    // Traverse the given array
    for(int i = 0; i < n - 1; i++)
    {
        prefix_sum += arr[i];
 
        // To store minimum difference
        int diff = abs((total_sum -
                       prefix_sum) -
                       prefix_sum);
 
        // Update minDiff
        if (diff < minDiff)
            minDiff = diff;
    }
 
    // Return minDiff
    return minDiff;
}
 
// Driver code
int main()
{
     
    // Given array
    int arr[] = { 7, 9, 5, 10 };
 
    // Length of the array
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << minDiffSubArray(arr, n) << endl;
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07


Java
// Java Program for above approach
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to return minimum difference
    // between sum of two subarrays
    static int minDiffSubArray(int arr[], int n)
    {
        // To store total sum of array
        int total_sum = 0;
 
        // Calculate the total sum
        // of the array
        for (int i = 0; i < n; i++)
            total_sum += arr[i];
 
        // Stores the prefix sum
        int prefix_sum = 0;
 
        // Stores the minimum difference
        int minDiff = Integer.MAX_VALUE;
 
        // Traverse the given array
        for (int i = 0; i < n - 1; i++) {
 
            prefix_sum += arr[i];
 
            // To store minimum difference
            int diff
                = Math.abs((total_sum
                            - prefix_sum)
                           - prefix_sum);
 
            // Update minDiff
            if (diff < minDiff)
                minDiff = diff;
        }
 
        // Return minDiff
        return minDiff;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array
        int[] arr = { 7, 9, 5, 10 };
 
        // Length of the array
        int n = arr.length;
 
        System.out.println(
            minDiffSubArray(arr, n));
    }
}


Python3
# Python3 program for the above approach
import sys
 
# Function to return minimum difference
# between sum of two subarrays
def minDiffSubArray(arr, n):
     
    # To store total sum of array
    total_sum = 0
 
    # Calculate the total sum
    # of the array
    for i in range(n):
        total_sum += arr[i]
 
    # Stores the prefix sum
    prefix_sum = 0
 
    # Stores the minimum difference
    minDiff = sys.maxsize
 
    # Traverse the given array
    for i in range(n - 1):
        prefix_sum += arr[i]
 
        # To store minimum difference
        diff = abs((total_sum -
                   prefix_sum) -
                   prefix_sum)
 
        # Update minDiff
        if (diff < minDiff):
            minDiff = diff
 
    # Return minDiff
    return minDiff
 
# Driver code
     
# Given array
arr = [ 7, 9, 5, 10 ]
 
# Length of the array
n = len(arr)
 
print(minDiffSubArray(arr, n))
 
# This code is contributed by code_hunt


C#
// C# Program for above approach
using System;
class GFG{
 
// Function to return minimum difference
// between sum of two subarrays
static int minDiffSubArray(int []arr,
                           int n)
{
  // To store total sum of array
  int total_sum = 0;
 
  // Calculate the total sum
  // of the array
  for (int i = 0; i < n; i++)
    total_sum += arr[i];
 
  // Stores the prefix sum
  int prefix_sum = 0;
 
  // Stores the minimum difference
  int minDiff = int.MaxValue;
 
  // Traverse the given array
  for (int i = 0; i < n - 1; i++)
  {
    prefix_sum += arr[i];
 
    // To store minimum difference
    int diff = Math.Abs((total_sum -
                         prefix_sum) -
                         prefix_sum);
 
    // Update minDiff
    if (diff < minDiff)
      minDiff = diff;
  }
 
  // Return minDiff
  return minDiff;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array
  int[] arr = {7, 9, 5, 10};
 
  // Length of the array
  int n = arr.Length;
 
  Console.WriteLine(
          minDiffSubArray(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
1

高效方法:对上述方法进行优化,其思想是计算数组元素的总和。现在,迭代数组并计算数组的前缀和,并找到数组的任何索引的前缀和与总和与前缀和之间的差值之间的最小差异,即,

下面是上述方法的实现:

C++

// C++ program for above approach
#include 
using namespace std;
 
// Function to return minimum difference
// between sum of two subarrays
int minDiffSubArray(int arr[], int n)
{
     
    // To store total sum of array
    int total_sum = 0;
 
    // Calculate the total sum
    // of the array
    for(int i = 0; i < n; i++)
        total_sum += arr[i];
 
    // Stores the prefix sum
    int prefix_sum = 0;
 
    // Stores the minimum difference
    int minDiff = INT_MAX;
 
    // Traverse the given array
    for(int i = 0; i < n - 1; i++)
    {
        prefix_sum += arr[i];
 
        // To store minimum difference
        int diff = abs((total_sum -
                       prefix_sum) -
                       prefix_sum);
 
        // Update minDiff
        if (diff < minDiff)
            minDiff = diff;
    }
 
    // Return minDiff
    return minDiff;
}
 
// Driver code
int main()
{
     
    // Given array
    int arr[] = { 7, 9, 5, 10 };
 
    // Length of the array
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << minDiffSubArray(arr, n) << endl;
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07

Java

// Java Program for above approach
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to return minimum difference
    // between sum of two subarrays
    static int minDiffSubArray(int arr[], int n)
    {
        // To store total sum of array
        int total_sum = 0;
 
        // Calculate the total sum
        // of the array
        for (int i = 0; i < n; i++)
            total_sum += arr[i];
 
        // Stores the prefix sum
        int prefix_sum = 0;
 
        // Stores the minimum difference
        int minDiff = Integer.MAX_VALUE;
 
        // Traverse the given array
        for (int i = 0; i < n - 1; i++) {
 
            prefix_sum += arr[i];
 
            // To store minimum difference
            int diff
                = Math.abs((total_sum
                            - prefix_sum)
                           - prefix_sum);
 
            // Update minDiff
            if (diff < minDiff)
                minDiff = diff;
        }
 
        // Return minDiff
        return minDiff;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array
        int[] arr = { 7, 9, 5, 10 };
 
        // Length of the array
        int n = arr.length;
 
        System.out.println(
            minDiffSubArray(arr, n));
    }
}

蟒蛇3

# Python3 program for the above approach
import sys
 
# Function to return minimum difference
# between sum of two subarrays
def minDiffSubArray(arr, n):
     
    # To store total sum of array
    total_sum = 0
 
    # Calculate the total sum
    # of the array
    for i in range(n):
        total_sum += arr[i]
 
    # Stores the prefix sum
    prefix_sum = 0
 
    # Stores the minimum difference
    minDiff = sys.maxsize
 
    # Traverse the given array
    for i in range(n - 1):
        prefix_sum += arr[i]
 
        # To store minimum difference
        diff = abs((total_sum -
                   prefix_sum) -
                   prefix_sum)
 
        # Update minDiff
        if (diff < minDiff):
            minDiff = diff
 
    # Return minDiff
    return minDiff
 
# Driver code
     
# Given array
arr = [ 7, 9, 5, 10 ]
 
# Length of the array
n = len(arr)
 
print(minDiffSubArray(arr, n))
 
# This code is contributed by code_hunt

C#

// C# Program for above approach
using System;
class GFG{
 
// Function to return minimum difference
// between sum of two subarrays
static int minDiffSubArray(int []arr,
                           int n)
{
  // To store total sum of array
  int total_sum = 0;
 
  // Calculate the total sum
  // of the array
  for (int i = 0; i < n; i++)
    total_sum += arr[i];
 
  // Stores the prefix sum
  int prefix_sum = 0;
 
  // Stores the minimum difference
  int minDiff = int.MaxValue;
 
  // Traverse the given array
  for (int i = 0; i < n - 1; i++)
  {
    prefix_sum += arr[i];
 
    // To store minimum difference
    int diff = Math.Abs((total_sum -
                         prefix_sum) -
                         prefix_sum);
 
    // Update minDiff
    if (diff < minDiff)
      minDiff = diff;
  }
 
  // Return minDiff
  return minDiff;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array
  int[] arr = {7, 9, 5, 10};
 
  // Length of the array
  int n = arr.Length;
 
  Console.WriteLine(
          minDiffSubArray(arr, n));
}
}
 
// This code is contributed by Rajput-Ji

Javascript


输出:
1

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live