📌  相关文章
📜  将数组分成两个子数组,使它们的平均值相等

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

将数组分成两个子数组,使它们的平均值相等

给定一个整数数组,任务是将一个整数数组分成两个子数组,以使它们的平均值尽可能相等。
例子 :

Input : arr[] = {1, 5, 7, 2, 0};    
Output : (0  1) and (2  4) 
Subarrays arr[0..1] and arr[2..4] have
same average.

Input : arr[] = {4, 3, 5, 9, 11};
Output : Not possible

在微软问

一种朴素的方法是运行两个循环并找到平均值相等的子数组。

C++
// Simple C++ program to find subarrays
// whose averages are equal
#include
using namespace std;
 
// Finding two subarrays
// with equal average.
void findSubarrays(int arr[], int n)
{
    bool found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = 0;
        for (int j = i + 1; j < n; j++)
            rsum += arr[j];
 
        // If averages of arr[0...i] and
        // arr[i+1..n-1] are same. To avoid
        // floating point problems we compare
        // "lsum*(n-i+1)" and "rsum*(i+1)"
        // instead of "lsum/(i+1)" and
        // "rsum/(n-i+1)"
        if (lsum * (n - i - 1) ==
               rsum * (i + 1))
        {
            printf("From (%d %d) to (%d %d)\n",
                           0, i, i + 1, n - 1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        cout << "Subarrays not found"
             << endl;
}
 
// Driver code
int main()
{
    int arr[] = {1, 5, 7, 2, 0};
    int n = sizeof(arr) / sizeof(arr[0]);
    findSubarrays(arr, n);
    return 0;
}


Java
// Simple Java program to find subarrays
// whose averages are equal
 
public class GFG {
     
    // Finding two subarrays
    // with equal average.
    static void findSubarrays(int[] arr, int n)
    {
        boolean found = false;
        int lsum = 0;
         
        for (int i = 0; i < n - 1; i++)
        {
            lsum += arr[i];
            int rsum = 0;
             
            for (int j = i + 1; j < n; j++)
                rsum += arr[j];
     
            // If averages of arr[0...i] and
            // arr[i+1..n-1] are same. To avoid
            // floating point problems we compare
            // "lsum*(n-i+1)" and "rsum*(i+1)"
            // instead of "lsum/(i+1)" and
            // "rsum/(n-i+1)"
            if (lsum * (n - i - 1) ==
                                rsum * (i + 1))
            {
                System.out.println("From (0 " + i
                        + ") to (" +(i + 1) + " "
                                + (n - 1)+ ")");
                             
                found = true;
            }
        }
     
        // If no subarrays found
        if (found == false)
            System.out.println( "Subarrays not "
                                    + "found");
    }
     
    // Driver code
    static public void main (String[] args)
    {
        int[] arr = {1, 5, 7, 2, 0};
        int n = arr.length;
        findSubarrays(arr, n);
    }
}
 
// This code is contributed by Mukul Singh.


Python 3
# Simple Python 3 program to find subarrays
# whose averages are equal
 
# Finding two subarrays with equal average.
def findSubarrays(arr, n):
 
    found = False
    lsum = 0
    for i in range(n - 1):
     
        lsum += arr[i]
        rsum = 0
        for j in range(i + 1, n):
            rsum += arr[j]
 
        # If averages of arr[0...i] and
        # arr[i+1..n-1] are same. To avoid
        # floating point problems we compare
        # "lsum*(n-i+1)" and "rsum*(i+1)"
        # instead of "lsum/(i+1)" and
        # "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1)):
            print("From", "(", 0, i, ")",
                  "to", "(", i + 1, n - 1, ")")
            found = True
 
    # If no subarrays found
    if (found == False):
        print("Subarrays not found")
 
# Driver code
if __name__ == "__main__":
     
    arr = [1, 5, 7, 2, 0]
    n = len(arr)
    findSubarrays(arr, n)
 
# This code is contributed by ita_c


C#
// Simple C# program to find subarrays
// whose averages are equal
using System;
 
public class GFG {
     
    // Finding two subarrays
    // with equal average.
    static void findSubarrays(int []arr, int n)
    {
        bool found = false;
        int lsum = 0;
         
        for (int i = 0; i < n - 1; i++)
        {
            lsum += arr[i];
            int rsum = 0;
             
            for (int j = i + 1; j < n; j++)
                rsum += arr[j];
     
            // If averages of arr[0...i] and
            // arr[i+1..n-1] are same. To avoid
            // floating point problems we compare
            // "lsum*(n-i+1)" and "rsum*(i+1)"
            // instead of "lsum/(i+1)" and
            // "rsum/(n-i+1)"
            if (lsum * (n - i - 1) ==
                                  rsum * (i + 1))
            {
                Console.WriteLine("From ( 0 " + i
                        + ") to(" + (i + 1) + " "
                                + (n - 1) + ")");
                             
                found = true;
            }
        }
     
        // If no subarrays found
        if (found == false)
            Console.WriteLine( "Subarrays not "
                                    + "found");
    }
     
    // Driver code
    static public void Main ()
    {
        int []arr = {1, 5, 7, 2, 0};
        int n = arr.Length;
        findSubarrays(arr, n);
    }
}
 
// This code is contributed by anuj_67.


PHP


Javascript


C++
// Efficient C++ program for
// dividing array to make
// average equal
#include
using namespace std;
 
void findSubarrays(int arr[], int n)
{
    // Find array sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    bool found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = sum - lsum;
 
        // If averages of arr[0...i]
        // and arr[i+1..n-1] are same.
        // To avoid floating point problems
        // we compare "lsum*(n-i+1)"
        // and "rsum*(i+1)" instead of
        // "lsum/(i+1)" and "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1))
        {
            printf("From (%d %d) to (%d %d)\n",
                               0, i, i+1, n-1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        cout << "Subarrays not found"
             << endl;
}
 
// Driver code
int main()
{
    int arr[] = {1, 5, 7, 2, 0};
    int n = sizeof(arr) / sizeof(arr[0]);
    findSubarrays(arr, n);
    return 0;
}


Java
// Efficient Java program for
// dividing array to make
// average equal
import java.util.*;
     
class GFG
{
static void findSubarrays(int arr[], int n)
{
    // Find array sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    boolean found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = sum - lsum;
 
        // If averages of arr[0...i]
        // and arr[i+1..n-1] are same.
        // To avoid floating point problems
        // we compare "lsum*(n-i+1)"
        // and "rsum*(i+1)" instead of
        // "lsum/(i+1)" and "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1))
        {
            System.out.printf("From (%d %d) to (%d %d)\n",
                                      0, i, i + 1, n - 1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        System.out.println("Subarrays not found");
}
 
// Driver code
static public void main ( String []arg)
{
    int arr[] = {1, 5, 7, 2, 0};
    int n = arr.length;
    findSubarrays(arr, n);
}
}
 
// This code is contributed by Princi Singh


Python3
# Efficient Python program for
# dividing array to make
# average equal
 
def findSubarrays(arr, n):
 
    # Find array sum
    sum = 0;
    for i in range(n):
        sum += arr[i];
 
    found = False;
    lsum = 0;
    for i in range(n - 1):
        lsum += arr[i];
        rsum = sum - lsum;
 
        # If averages of arr[0...i]
        # and arr[i + 1..n - 1] are same.
        # To avoid floating poproblems
        # we compare "lsum*(n - i + 1)"
        # and "rsum*(i + 1)" instead of
        # "lsum / (i + 1)" and "rsum/(n - i + 1)"
        if (lsum * (n - i - 1) == rsum * (i + 1)):
            print("From (%d %d) to (%d %d)\n"%
                   (0, i, i + 1, n - 1));
            found = True;
         
    # If no subarrays found
    if (found == False):
        print("Subarrays not found");
 
# Driver code
if __name__ == '__main__':
    arr = [ 1, 5, 7, 2, 0 ];
    n = len(arr);
    findSubarrays(arr, n);
 
# This code is contributed by Rajput-Ji


C#
// Efficient C# program for
// dividing array to make
// average equal
using System;
     
class GFG
{
static void findSubarrays(int []arr, int n)
{
    // Find array sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    bool found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = sum - lsum;
 
        // If averages of arr[0...i]
        // and arr[i+1..n-1] are same.
        // To avoid floating point problems
        // we compare "lsum*(n-i+1)"
        // and "rsum*(i+1)" instead of
        // "lsum/(i+1)" and "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1))
        {
            Console.Write("From ({0} {1}) to ({2} {3})\n",
                                      0, i, i + 1, n - 1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        Console.WriteLine("Subarrays not found");
}
 
// Driver code
static public void Main ( String []arg)
{
    int []arr = {1, 5, 7, 2, 0};
    int n = arr.Length;
    findSubarrays(arr, n);
}
}
     
// This code is contributed by Rajput-Ji


Javascript


输出 :

From (0  1) to (2  4)

时间复杂度: O(n 2 )
辅助空间: O(1)
一个有效的解决方案是找到数组元素的总和。将leftsum初始化为零。运行一个循环并通过添加数组元素来找到leftsum。对于rightsum,我们从总和中减去leftsum,然后我们找到rightsum,并根据它们的索引找到leftsum和rightsum的平均值。

1) Compute sum of all array elements. Let this 
   sum be "sum"
2) Initialize leftsum = 0.
3) Run a loop for i=0 to n-1.
    a) leftsum  = leftsum + arr[i]
    b) rightsum = sum - leftsum
    c) If average of left and right are same, 
       print current index as output.

以下是上述方法的实现:

C++

// Efficient C++ program for
// dividing array to make
// average equal
#include
using namespace std;
 
void findSubarrays(int arr[], int n)
{
    // Find array sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    bool found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = sum - lsum;
 
        // If averages of arr[0...i]
        // and arr[i+1..n-1] are same.
        // To avoid floating point problems
        // we compare "lsum*(n-i+1)"
        // and "rsum*(i+1)" instead of
        // "lsum/(i+1)" and "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1))
        {
            printf("From (%d %d) to (%d %d)\n",
                               0, i, i+1, n-1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        cout << "Subarrays not found"
             << endl;
}
 
// Driver code
int main()
{
    int arr[] = {1, 5, 7, 2, 0};
    int n = sizeof(arr) / sizeof(arr[0]);
    findSubarrays(arr, n);
    return 0;
}

Java

// Efficient Java program for
// dividing array to make
// average equal
import java.util.*;
     
class GFG
{
static void findSubarrays(int arr[], int n)
{
    // Find array sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    boolean found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = sum - lsum;
 
        // If averages of arr[0...i]
        // and arr[i+1..n-1] are same.
        // To avoid floating point problems
        // we compare "lsum*(n-i+1)"
        // and "rsum*(i+1)" instead of
        // "lsum/(i+1)" and "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1))
        {
            System.out.printf("From (%d %d) to (%d %d)\n",
                                      0, i, i + 1, n - 1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        System.out.println("Subarrays not found");
}
 
// Driver code
static public void main ( String []arg)
{
    int arr[] = {1, 5, 7, 2, 0};
    int n = arr.length;
    findSubarrays(arr, n);
}
}
 
// This code is contributed by Princi Singh

Python3

# Efficient Python program for
# dividing array to make
# average equal
 
def findSubarrays(arr, n):
 
    # Find array sum
    sum = 0;
    for i in range(n):
        sum += arr[i];
 
    found = False;
    lsum = 0;
    for i in range(n - 1):
        lsum += arr[i];
        rsum = sum - lsum;
 
        # If averages of arr[0...i]
        # and arr[i + 1..n - 1] are same.
        # To avoid floating poproblems
        # we compare "lsum*(n - i + 1)"
        # and "rsum*(i + 1)" instead of
        # "lsum / (i + 1)" and "rsum/(n - i + 1)"
        if (lsum * (n - i - 1) == rsum * (i + 1)):
            print("From (%d %d) to (%d %d)\n"%
                   (0, i, i + 1, n - 1));
            found = True;
         
    # If no subarrays found
    if (found == False):
        print("Subarrays not found");
 
# Driver code
if __name__ == '__main__':
    arr = [ 1, 5, 7, 2, 0 ];
    n = len(arr);
    findSubarrays(arr, n);
 
# This code is contributed by Rajput-Ji

C#

// Efficient C# program for
// dividing array to make
// average equal
using System;
     
class GFG
{
static void findSubarrays(int []arr, int n)
{
    // Find array sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += arr[i];
 
    bool found = false;
    int lsum = 0;
    for (int i = 0; i < n - 1; i++)
    {
        lsum += arr[i];
        int rsum = sum - lsum;
 
        // If averages of arr[0...i]
        // and arr[i+1..n-1] are same.
        // To avoid floating point problems
        // we compare "lsum*(n-i+1)"
        // and "rsum*(i+1)" instead of
        // "lsum/(i+1)" and "rsum/(n-i+1)"
        if (lsum * (n - i - 1) == rsum * (i + 1))
        {
            Console.Write("From ({0} {1}) to ({2} {3})\n",
                                      0, i, i + 1, n - 1);
            found = true;
        }
    }
 
    // If no subarrays found
    if (found == false)
        Console.WriteLine("Subarrays not found");
}
 
// Driver code
static public void Main ( String []arg)
{
    int []arr = {1, 5, 7, 2, 0};
    int n = arr.Length;
    findSubarrays(arr, n);
}
}
     
// This code is contributed by Rajput-Ji

Javascript


输出 :

From (0  1) to (2  4)