Imprimir todos los subarreglos con suma en un rango dado

Dada una array arr[] de enteros positivos y dos enteros L y R que definen el rango [L, R] . La tarea es imprimir los subarreglos que tienen una suma en el rango L a R .

Ejemplos:  

Entrada: arr[] = {1, 4, 6}, L = 3, R = 8
Salida: {1, 4}, {4}, {6}.
Explicación: Todos los subarreglos posibles son los siguientes
{1] con suma 1. 
{1, 4} con suma 5. 
{1, 4, 6} con suma 11.
{4} con suma 4.
{4, 6} con suma 10. 
{6} con suma 6. 
Por lo tanto, los subarreglos {1, 4}, {4}, {6} tienen suma en el rango [3, 8].

Entrada: arr[] = {2, 3, 5, 8}, L = 4, R = 13
Salida:  {2, 3}, {2, 3, 5}, {3, 5}, {5}, { 5, 8}, {8}.

 

Enfoque: este problema se puede resolver haciendo fuerza bruta y verificando todos y cada uno de los subarreglos posibles usando dos bucles. A continuación se muestra la implementación del enfoque anterior. 

C++

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find subarrays in given range
void subArraySum(int arr[], int n,
                 int leftsum, int rightsum)
{
    int curr_sum, i, j, res = 0;
 
    // Pick a starting point
    for (i = 0; i < n; i++) {
        curr_sum = arr[i];
 
        // Try all subarrays starting with 'i'
        for (j = i + 1; j <= n; j++) {
            if (curr_sum > leftsum
                && curr_sum < rightsum) {
                cout << "{ ";
 
                for (int k = i; k < j; k++)
                    cout << arr[k] << " ";
 
                cout << "}\n";
            }
            if (curr_sum > rightsum || j == n)
                break;
            curr_sum = curr_sum + arr[j];
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int L = 10, R = 23;
 
    subArraySum(arr, N, L, R);
 
    return 0;
}

Java

// Java code for the above approach
import java.io.*;
 
class GFG
{
   
    // Function to find subarrays in given range
    static void subArraySum(int arr[], int n, int leftsum,
                            int rightsum)
    {
        int curr_sum, i, j, res = 0;
 
        // Pick a starting point
        for (i = 0; i < n; i++) {
            curr_sum = arr[i];
 
            // Try all subarrays starting with 'i'
            for (j = i + 1; j <= n; j++) {
                if (curr_sum > leftsum
                    && curr_sum < rightsum) {
                    System.out.print("{ ");
 
                    for (int k = i; k < j; k++)
                        System.out.print(arr[k] + " ");
 
                    System.out.println("}");
                }
                if (curr_sum > rightsum || j == n)
                    break;
                curr_sum = curr_sum + arr[j];
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
        int N = arr.length;
 
        int L = 10, R = 23;
 
        subArraySum(arr, N, L, R);
    }
}
 
// This code is contributed by Potta Lokesh

Python3

# Python program for above approach
 
# Function to find subarrays in given range
def subArraySum (arr, n, leftsum, rightsum):
    res = 0
 
    # Pick a starting point
    for i in range(n):
        curr_sum = arr[i]
 
        # Try all subarrays starting with 'i'
        for j in range(i + 1, n + 1):
            if (curr_sum > leftsum
                and curr_sum < rightsum):
                print("{ ", end="")
 
                for k in range(i, j):
                    print(arr[k], end=" ")
 
                print("}")
            if (curr_sum > rightsum or j == n):
                break
            curr_sum = curr_sum + arr[j]
         
# Driver Code
arr = [15, 2, 4, 8, 9, 5, 10, 23]
N = len(arr)
L = 10
R = 23
subArraySum(arr, N, L, R)
 
# This code is contributed by Saurabh Jaiswal

C#

// C# code for the above approach
using System;
 
class GFG
{
   
    // Function to find subarrays in given range
    static void subArraySum(int []arr, int n, int leftsum,
                            int rightsum)
    {
        int curr_sum, i, j, res = 0;
 
        // Pick a starting point
        for (i = 0; i < n; i++) {
            curr_sum = arr[i];
 
            // Try all subarrays starting with 'i'
            for (j = i + 1; j <= n; j++) {
                if (curr_sum > leftsum
                    && curr_sum < rightsum) {
                    Console.Write("{ ");
 
                    for (int k = i; k < j; k++)
                        Console.Write(arr[k] + " ");
 
                    Console.WriteLine("}");
                }
                if (curr_sum > rightsum || j == n)
                    break;
                curr_sum = curr_sum + arr[j];
            }
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int []arr = { 15, 2, 4, 8, 9, 5, 10, 23 };
        int N = arr.Length;
 
        int L = 10, R = 23;
 
        subArraySum(arr, N, L, R);
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript

<script>
    // JavaScript program for above approach
 
    // Function to find subarrays in given range
    const subArraySum = (arr, n, leftsum, rightsum) => {
        let curr_sum, i, j, res = 0;
 
        // Pick a starting point
        for (i = 0; i < n; i++) {
            curr_sum = arr[i];
 
            // Try all subarrays starting with 'i'
            for (j = i + 1; j <= n; j++) {
                if (curr_sum > leftsum
                    && curr_sum < rightsum) {
                    document.write("{ ");
 
                    for (let k = i; k < j; k++)
                        document.write(`${arr[k]} `);
 
                    document.write("}<br/>");
                }
                if (curr_sum > rightsum || j == n)
                    break;
                curr_sum = curr_sum + arr[j];
            }
        }
    }
 
    // Driver Code
    let arr = [15, 2, 4, 8, 9, 5, 10, 23];
    let N = arr.length;
    let L = 10, R = 23;
    subArraySum(arr, N, L, R);
 
    // This code is contributed by rakeshsahni
 
</script>
Producción

{ 15 }
{ 15 2 }
{ 15 2 4 }
{ 2 4 8 }
{ 4 8 }
{ 4 8 9 }
{ 8 9 }
{ 8 9 5 }
{ 9 5 }
{ 5 10 }

Complejidad de tiempo: O(N^3)

Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por Code_r y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *