Maximice la suma de subarreglo de Array dado agregando X en el rango [L, R] para consultas Q

Dada una array arr[] de N enteros y M consultas de actualización del tipo (L, R, X) , la tarea es encontrar la suma máxima de subarreglo después de cada consulta de actualización donde en cada consulta, agregue el entero X a cada elemento de la array arr[] en el rango [L, R] .

Ejemplos:

Entrada: arr[] = {-1, 5, -2, 9, 3, -3, 2}, consulta[] = {{0, 2, -10}, {4, 5, 2}}
Salida: 12 15
Explicación: A continuación se muestran los pasos para resolver el ejemplo anterior:

  • La array después de la primera consulta de actualización se convierte en arr[] = {-11, -5, -12, 9, 3, -3, 2}. Por lo tanto, la suma máxima de subarreglo es 12 del subarreglo arr[3… 4].
  • La array después de la segunda consulta de actualización se convierte en arr[] = {-11, -5, -12, 9, 5, -1, 2}. Por lo tanto, la suma máxima de subarreglo es 15 del subarreglo arr[3… 6].

Entrada: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6, 4, -1}, consulta[] = {{1, 4, 3}, {4, 5, -4}, {7, 9, 5}}
Salida: 16 10 20

 

Enfoque: El problema dado se puede resolver utilizando el Algoritmo de Kadane . Para cada consulta, actualice los elementos de la array recorriendo todos los elementos de la array arr[] en el rango [L, R] y agregue el entero X a cada elemento. Después de cada consulta de actualización, calcule la suma máxima de subarreglo utilizando el algoritmo que se describe aquí

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

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum subarray
// sum using Kadane's Algorithm
int maxSubarraySum(int arr[], int n)
{
    // Stores the maximum sum
    int maxSum = INT_MIN;
    int currSum = 0;
 
    // Loop to iterate over the array
    for (int i = 0; i <= n - 1; i++) {
        currSum += arr[i];
 
        // Update maxSum
        if (currSum > maxSum) {
            maxSum = currSum;
        }
        if (currSum < 0) {
            currSum = 0;
        }
    }
 
    // Return Answer
    return maxSum;
}
 
// Function to add integer X to all elements
// of the given array in range [L, R]
void updateArr(int* arr, int L, int R, int X)
{
    // Loop to iterate over the range
    for (int i = L; i <= R; i++) {
        arr[i] += X;
    }
}
 
// Function to find the maximum subarray sum
// after each range update query
void maxSubarraySumQuery(
    int arr[], int n,
    vector<vector<int> > query)
{
    // Loop to iterate over the queries
    for (int i = 0; i < query.size(); i++) {
 
        // Function call to update the array
        // according to the mentioned query
        updateArr(arr, query[i][0],
                  query[i][1],
                  query[i][2]);
 
        // Print the max subarray sum after
        // updating the given array
        cout << maxSubarraySum(arr, n) << " ";
    }
}
 
// Driver Code
int main()
{
 
    int arr[] = { -2, -5, 6, -2, -3,
                  1, 5, -6, 4, -1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    vector<vector<int> > query{ { 1, 4, 3 },
                                { 4, 5, -4 },
                                { 7, 9, 5 } };
 
    maxSubarraySumQuery(arr, N, query);
 
    return 0;
}

Java

// Java  program for the above approach
class GFG {
 
    // Function to find the maximum subarray
    // sum using Kadane's Algorithm
    public static int maxSubarraySum(int arr[], int n)
    {
       
        // Stores the maximum sum
        int maxSum = Integer.MIN_VALUE;
        int currSum = 0;
 
        // Loop to iterate over the array
        for (int i = 0; i <= n - 1; i++) {
            currSum += arr[i];
 
            // Update maxSum
            if (currSum > maxSum) {
                maxSum = currSum;
            }
            if (currSum < 0) {
                currSum = 0;
            }
        }
 
        // Return Answer
        return maxSum;
    }
 
    // Function to add integer X to all elements
    // of the given array in range [L, R]
    public static void updateArr(int[] arr, int L,
                                 int R, int X)
    {
       
        // Loop to iterate over the range
        for (int i = L; i <= R; i++) {
            arr[i] += X;
        }
    }
 
    // Function to find the maximum subarray sum
    // after each range update query
    public static void maxSubarraySumQuery(int arr[], int n, int[][] query)
    {
       
        // Loop to iterate over the queries
        for (int i = 0; i < query.length; i++)
        {
 
            // Function call to update the array
            // according to the mentioned query
            updateArr(arr, query[i][0],
                    query[i][1],
                    query[i][2]);
 
            // Print the max subarray sum after
            // updating the given array
            System.out.print(maxSubarraySum(arr, n) + " ");
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { -2, -5, 6, -2, -3,
                1, 5, -6, 4, -1 };
        int N = arr.length;
        int[][] query = { { 1, 4, 3 }, { 4, 5, -4 }, { 7, 9, 5 } };
        maxSubarraySumQuery(arr, N, query);
    }
}
 
// This code is contributed by saurabh_jaiswal.

Python3

# Python Program to implement
# the above approach
 
# Function to find the maximum subarray
# sum using Kadane's Algorithm
def maxSubarraySum(arr, n):
 
    # Stores the maximum sum
    maxSum = 10 ** -9
    currSum = 0
 
    # Loop to iterate over the array
    for i in range(n):
        currSum += arr[i]
 
        # Update maxSum
        if (currSum > maxSum):
            maxSum = currSum
        if (currSum < 0):
            currSum = 0
    # Return Answer
    return maxSum
 
 
# Function to add integer X to all elements
# of the given array in range[L, R]
def updateArr(arr, L, R, X):
    # Loop to iterate over the range
    for i in range(L, R + 1):
        arr[i] += X
 
# Function to find the maximum subarray sum
# after each range update query
def maxSubarraySumQuery(arr, n, query):
   
    # Loop to iterate over the queries
    for i in range(len(query)):
 
        # Function call to update the array
        # according to the mentioned query
        updateArr(arr, query[i][0],
                  query[i][1],
                  query[i][2])
 
        # Print the max subarray sum after
        # updating the given array
        print(maxSubarraySum(arr, n), end=" ")
 
# Driver Code
arr = [-2, -5, 6, -2, -3, 1, 5, -6, 4, -1]
N = len(arr)
query = [[1, 4, 3],[4, 5, -4],[7, 9, 5]]
 
maxSubarraySumQuery(arr, N, query)
 
# This code is contributed by gfgking

C#

// C#  program for the above approach
using System;
class GFG
{
 
    // Function to find the maximum subarray
    // sum using Kadane's Algorithm
    public static int maxSubarraySum(int[] arr, int n)
    {
 
        // Stores the maximum sum
        int maxSum = int.MinValue;
        int currSum = 0;
 
        // Loop to iterate over the array
        for (int i = 0; i <= n - 1; i++)
        {
            currSum += arr[i];
 
            // Update maxSum
            if (currSum > maxSum)
            {
                maxSum = currSum;
            }
            if (currSum < 0)
            {
                currSum = 0;
            }
        }
 
        // Return Answer
        return maxSum;
    }
 
    // Function to add integer X to all elements
    // of the given array in range [L, R]
    public static void updateArr(int[] arr, int L,
                                 int R, int X)
    {
 
        // Loop to iterate over the range
        for (int i = L; i <= R; i++)
        {
            arr[i] += X;
        }
    }
 
    // Function to find the maximum subarray sum
    // after each range update query
    public static void maxSubarraySumQuery(int[] arr, int n, int[,] query)
    {
 
        // Loop to iterate over the queries
        for (int i = 0; i < query.Length; i++)
        {
 
            // Function call to update the array
            // according to the mentioned query
            updateArr(arr, query[i, 0],
                    query[i, 1],
                    query[i, 2]);
 
            // Print the max subarray sum after
            // updating the given array
            Console.Write(maxSubarraySum(arr, n) + " ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { -2, -5, 6, -2, -3, 1, 5, -6, 4, -1 };
        int N = arr.Length;
        int[,] query = { { 1, 4, 3 }, { 4, 5, -4 }, { 7, 9, 5 } };
        maxSubarraySumQuery(arr, N, query);
    }
}
 
// This code is contributed by _saurabh_jaiswal.

Javascript

<script>
    // JavaScript Program to implement
    // the above approach
 
    // Function to find the maximum subarray
    // sum using Kadane's Algorithm
    function maxSubarraySum(arr, n)
    {
     
        // Stores the maximum sum
        let maxSum = Number.MIN_VALUE;
        let currSum = 0;
 
        // Loop to iterate over the array
        for (let i = 0; i <= n - 1; i++) {
            currSum += arr[i];
 
            // Update maxSum
            if (currSum > maxSum) {
                maxSum = currSum;
            }
            if (currSum < 0) {
                currSum = 0;
            }
        }
 
        // Return Answer
        return maxSum;
    }
 
    // Function to add integer X to all elements
    // of the given array in range [L, R]
    function updateArr(arr, L, R, X) {
        // Loop to iterate over the range
        for (let i = L; i <= R; i++) {
            arr[i] += X;
        }
    }
 
    // Function to find the maximum subarray sum
    // after each range update query
    function maxSubarraySumQuery(
        arr, n,
        query) {
        // Loop to iterate over the queries
        for (let i = 0; i < query.length; i++) {
 
            // Function call to update the array
            // according to the mentioned query
            updateArr(arr, query[i][0],
                query[i][1],
                query[i][2]);
 
            // Print the max subarray sum after
            // updating the given array
            document.write(maxSubarraySum(arr, n) + " ");
        }
    }
 
    // Driver Code
    let arr = [-2, -5, 6, -2, -3,
        1, 5, -6, 4, -1];
    let N = arr.length;
    let query = [[1, 4, 3],
    [4, 5, -4],
    [7, 9, 5]];
 
    maxSubarraySumQuery(arr, N, query);
 
// This code is contributed by Potta Lokesh
</script>
Producción

16 10 20 

Complejidad temporal: O(N*M)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

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