Maximize subarray sum of given Array by adding X in range [L, R] for Q queries
Last Updated :
06 Dec, 2021
Given an array arr[] of N integers and M update queries of the type (L, R, X), the task is to find the maximum subarray sum after each update query where in each query, add integer X to every element of the array arr[] in the range [L, R].
Examples:
Input: arr[] = {-1, 5, -2, 9, 3, -3, 2}, query[] = {{0, 2, -10}, {4, 5, 2}}
Output: 12 15
Explanation: Below are the steps to solve the above example:
- The array after 1st update query becomes arr[] = {-11, -5, -12, 9, 3, -3, 2}. Hence the maximum subarray sum is 12 of the subarray arr[3... 4].
- The array after 2nd update query becomes arr[] = {-11, -5, -12, 9, 5, -1, 2}. Hence the maximum subarray sum is 15 of the subarray arr[3... 6].
Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6, 4, -1}, query[] = {{1, 4, 3}, {4, 5, -4}, {7, 9, 5}}
Output: 16 10 20
Approach: The given problem can be solved using Kadane's Algorithm. For each query, update the array elements by traversing over all the elements of the array arr[] in the range [L, R] and add integer X to each element. After every update query, calculate the maximum subarray sum using the algorithm discussed here.
Below is the implementation of the above approach:
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>
Time Complexity: O(N*M)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read