Longitud máxima L tal que la suma de todos los subarreglos de longitud L es menor que K

Dada una array de longitud N y un número entero K. La tarea es encontrar la longitud máxima L tal que todos los subarreglos de longitud L tengan una suma de sus elementos menor que K .
Ejemplos: 

Entrada: arr[] = {1, 2, 3, 4, 5}, K = 20 
Salida:
El único subarreglo de longitud 5 es el 
arreglo completo y (1 + 2 + 3 + 4 + 5) = 15 < 20 .

Entrada: arr[] = {1, 2, 3, 4, 5}, K = 10 
Salida:

Método: para obtener la suma máxima de un subarreglo de longitud K , siga el método que se analiza en este artículo. Ahora, se puede realizar una búsqueda binaria para encontrar la longitud máxima. Como los elementos del conjunto son positivos, al aumentar la longitud del subarreglo aumentará la suma máxima de los elementos del subarreglo para esa longitud.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximum sum
// in a subarray of size k
int maxSum(int arr[], int n, int k)
{
    // k must be greater
    if (n < k) {
        return -1;
    }
 
    // Compute sum of first window of size k
    int res = 0;
    for (int i = 0; i < k; i++)
        res += arr[i];
 
    // Compute sums of remaining windows by
    // removing first element of previous
    // window and adding last element of
    // current window.
    int curr_sum = res;
    for (int i = k; i < n; i++) {
        curr_sum += arr[i] - arr[i - k];
        res = max(res, curr_sum);
    }
 
    return res;
}
 
// Function to return the length of subarray
// Sum of all the subarray of this
// length is less than or equal to K
int solve(int arr[], int n, int k)
{
    int max_len = 0, l = 0, r = n, m;
 
    // Binary search from l to r as all the
    // array elements are positive so that
    // the maximum subarray sum is monotonically
    // increasing
    while (l <= r) {
        m = (l + r) / 2;
 
        // Check if the subarray sum is
        // greater than K or not
        if (maxSum(arr, n, m) > k)
            r = m - 1;
        else {
            l = m + 1;
 
            // Update the maximum length
            max_len = m;
        }
    }
    return max_len;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(arr) / sizeof(int);
    int k = 10;
 
    cout << solve(arr, n, k);
 
    return 0;
}

Java

// Java implementation of the approach
class GFG
{
     
    // Function to return the maximum sum
    // in a subarray of size k
    static int maxSum(int arr[], int n, int k)
    {
        // k must be greater
        if (n < k)
        {
            return -1;
        }
     
        // Compute sum of first window of size k
        int res = 0;
        for (int i = 0; i < k; i++)
            res += arr[i];
     
        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        int curr_sum = res;
        for (int i = k; i < n; i++)
        {
            curr_sum += arr[i] - arr[i - k];
            res = Math.max(res, curr_sum);
        }
     
        return res;
    }
     
    // Function to return the length of subarray
    // Sum of all the subarray of this
    // length is less than or equal to K
    static int solve(int arr[], int n, int k)
    {
        int max_len = 0, l = 0, r = n, m;
     
        // Binary search from l to r as all the
        // array elements are positive so that
        // the maximum subarray sum is monotonically
        // increasing
        while (l <= r)
        {
            m = (l + r) / 2;
     
            // Check if the subarray sum is
            // greater than K or not
            if (maxSum(arr, n, m) > k)
                r = m - 1;
            else
            {
                l = m + 1;
     
                // Update the maximum length
                max_len = m;
            }
        }
        return max_len;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5 };
        int n = arr.length;
         
        int k = 10;
     
        System.out.println(solve(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01

Python3

# Python3 implementation of the approach
 
# Function to return the maximum sum
# in a subarray of size k
def maxSum(arr, n, k) :
 
    # k must be greater
    if (n < k) :
        return -1;
 
    # Compute sum of first window of size k
    res = 0;
     
    for i in range(k) :
        res += arr[i];
 
    # Compute sums of remaining windows by
    # removing first element of previous
    # window and adding last element of
    # current window.
    curr_sum = res;
     
    for i in range(k, n) :
        curr_sum += arr[i] - arr[i - k];
        res = max(res, curr_sum);
 
    return res;
 
# Function to return the length of subarray
# Sum of all the subarray of this
# length is less than or equal to K
def solve(arr, n, k) :
 
    max_len = 0; l = 0; r = n;
 
    # Binary search from l to r as all the
    # array elements are positive so that
    # the maximum subarray sum is monotonically
    # increasing
    while (l <= r) :
        m = (l + r) // 2;
 
        # Check if the subarray sum is
        # greater than K or not
        if (maxSum(arr, n, m) > k) :
            r = m - 1;
        else :
            l = m + 1;
 
            # Update the maximum length
            max_len = m;
             
    return max_len;
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 2, 3, 4, 5 ];
    n = len(arr);
    k = 10;
 
    print(solve(arr, n, k));
 
# This code is contributed by AnkitRai01

C#

// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the maximum sum
    // in a subarray of size k
    static int maxSum(int []arr, int n, int k)
    {
        // k must be greater
        if (n < k)
        {
            return -1;
        }
     
        // Compute sum of first window of size k
        int res = 0;
        for (int i = 0; i < k; i++)
            res += arr[i];
     
        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        int curr_sum = res;
        for (int i = k; i < n; i++)
        {
            curr_sum += arr[i] - arr[i - k];
            res = Math.Max(res, curr_sum);
        }
        return res;
    }
     
    // Function to return the length of subarray
    // Sum of all the subarray of this
    // length is less than or equal to K
    static int solve(int []arr, int n, int k)
    {
        int max_len = 0, l = 0, r = n, m;
     
        // Binary search from l to r as all the
        // array elements are positive so that
        // the maximum subarray sum is monotonically
        // increasing
        while (l <= r)
        {
            m = (l + r) / 2;
     
            // Check if the subarray sum is
            // greater than K or not
            if (maxSum(arr, n, m) > k)
                r = m - 1;
            else
            {
                l = m + 1;
     
                // Update the maximum length
                max_len = m;
            }
        }
        return max_len;
    }
     
    // Driver code
    public static void Main ()
    {
        int []arr = { 1, 2, 3, 4, 5 };
        int n = arr.Length;
         
        int k = 10;
     
        Console.WriteLine(solve(arr, n, k));
    }
}
 
// This code is contributed by AnkitRai01

Javascript

<script>
 
// javascript implementation of the approach
 
// Function to return the maximum sum
// in a subarray of size k
    function maxSum(arr , n , k) {
        // k must be greater
        if (n < k) {
            return -1;
        }
 
        // Compute sum of first window of size k
        var res = 0;
        for (i = 0; i < k; i++)
            res += arr[i];
 
        // Compute sums of remaining windows by
        // removing first element of previous
        // window and adding last element of
        // current window.
        var curr_sum = res;
        for (i = k; i < n; i++) {
            curr_sum += arr[i] - arr[i - k];
            res = Math.max(res, curr_sum);
        }
 
        return res;
    }
 
    // Function to return the length of subarray
    // Sum of all the subarray of this
    // length is less than or equal to K
    function solve(arr , n , k) {
        var max_len = 0, l = 0, r = n, m;
 
        // Binary search from l to r as all the
        // array elements are positive so that
        // the maximum subarray sum is monotonically
        // increasing
        while (l <= r) {
            m = parseInt((l + r) / 2);
 
            // Check if the subarray sum is
            // greater than K or not
            if (maxSum(arr, n, m) > k)
                r = m - 1;
            else {
                l = m + 1;
 
                // Update the maximum length
                max_len = m;
            }
        }
        return max_len;
    }
 
    // Driver code
     
        var arr = [ 1, 2, 3, 4, 5 ];
        var n = arr.length;
 
        var k = 10;
 
        document.write(solve(arr, n, k));
 
// This code contributed by Rajput-Ji
 
</script>
Producción

2

Complejidad de tiempo: O(N*logN), ya que estamos usando una búsqueda binaria que costará logN y en cada recorrido llamamos a la función maxSum que costará O(N) tiempo. Donde N es el número de elementos de la array.
Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.

Publicación traducida automáticamente

Artículo escrito por andrew1234 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 *