Maximum value in an array after m range increment operations
Last Updated :
06 Mar, 2025
Consider an array of size n with all initial values as 0. We need to perform the following m range increment operations.
increment(a, b, k) : Increment values from 'a' to 'b' by 'k'.
After m operations, we need to calculate the maximum of the values in the array.
Examples:
Input : n = 5 m = 3
a = 0, b = 1, k = 100
a = 1, b = 4, k = 100
a = 2, b = 3, k = 100
Output : 200
Explanation:
Initially array = {0, 0, 0, 0, 0}
After first operation: {100, 100, 0, 0, 0}
After second operation: {100, 200, 100, 100, 100}
After third operation {100, 200, 200, 200, 100}
Maximum element after m operations is 200.
Input : n = 4 m = 3
a = 1, b = 2, k = 603
a = 0, b = 0, k = 286
a = 3, b = 3, k = 882
Output : 882
Explanation:
Initially array = {0, 0, 0, 0}
After first operation: {0, 603, 603, 0}
After second operation: {286, 603, 603, 0}
After third operation: {286, 603, 603, 882}
Maximum element after m operations is 882.
[Naive Approach] - One by One Increment
A naive method is to perform each operation on the given range and then, at last, find the maximum number.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the maximum element after
// m operations
int findMax(int n, vector<int>& a, vector<int>& b,
vector<int>& k) {
vector<int> arr(n, 0);
// start performing m operations
for (int i = 0; i < a.size(); i++) {
// Store lower and upper index i.e. range
int lowerbound = a[i];
int upperbound = b[i];
// Add 'k[i]' value at this operation to
// whole range
for (int j = lowerbound; j <= upperbound; j++)
arr[j] += k[i];
}
// Find maximum value after all operations and
// return
int res = INT_MIN;
for (int i = 0; i < n; i++)
res = max(res, arr[i]);
return res;
}
// Driver code
int main() {
// Number of queries
int n = 5;
vector<int> a = {0, 1, 2};
vector<int> b = {1, 4, 3};
// value of k to be added at each operation
vector<int> k = {100, 100, 100};
cout << "Maximum value after 'm' operations is "
<< findMax(n, a, b, k);
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Function to find the maximum element after
// m operations
public static int findMax(int n, int[] a, int[] b, int[] k) {
int[] arr = new int[n];
// start performing m operations
for (int i = 0; i < a.length; i++) {
// Store lower and upper index i.e. range
int lowerbound = a[i];
int upperbound = b[i];
// Add 'k[i]' value at this operation to
// whole range
for (int j = lowerbound; j <= upperbound; j++)
arr[j] += k[i];
}
// Find maximum value after all operations and
// return
int res = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
res = Math.max(res, arr[i]);
return res;
}
// Driver code
public static void main(String[] args) {
// Number of queries
int n = 5;
int[] a = {0, 1, 2};
int[] b = {1, 4, 3};
// value of k to be added at each operation
int[] k = {100, 100, 100};
System.out.println("Maximum value after 'm' operations is " + findMax(n, a, b, k));
}
}
Python
# Function to find the maximum element after
# m operations
def find_max(n, a, b, k):
arr = [0] * n
# start performing m operations
for i in range(len(a)):
# Store lower and upper index i.e. range
lowerbound = a[i]
upperbound = b[i]
# Add 'k[i]' value at this operation to
# whole range
for j in range(lowerbound, upperbound + 1):
arr[j] += k[i]
# Find maximum value after all operations and
# return
res = float('-inf')
for i in range(n):
res = max(res, arr[i])
return res
# Driver code
if __name__ == '__main__':
# Number of queries
n = 5
a = [0, 1, 2]
b = [1, 4, 3]
# value of k to be added at each operation
k = [100, 100, 100]
print("Maximum value after 'm' operations is ", find_max(n, a, b, k))
C#
using System;
using System.Linq;
class Program {
// Function to find the maximum element after
// m operations
public static int FindMax(int n, int[] a, int[] b, int[] k) {
int[] arr = new int[n];
// start performing m operations
for (int i = 0; i < a.Length; i++) {
// Store lower and upper index i.e. range
int lowerbound = a[i];
int upperbound = b[i];
// Add 'k[i]' value at this operation to
// whole range
for (int j = lowerbound; j <= upperbound; j++)
arr[j] += k[i];
}
// Find maximum value after all operations and
// return
int res = int.MinValue;
for (int i = 0; i < n; i++)
res = Math.Max(res, arr[i]);
return res;
}
// Driver code
static void Main() {
// Number of queries
int n = 5;
int[] a = {0, 1, 2};
int[] b = {1, 4, 3};
// value of k to be added at each operation
int[] k = {100, 100, 100};
Console.WriteLine("Maximum value after 'm' operations is " + FindMax(n, a, b, k));
}
}
JavaScript
// Function to find the maximum element after
// m operations
function findMax(n, a, b, k) {
let arr = new Array(n).fill(0);
// start performing m operations
for (let i = 0; i < a.length; i++) {
// Store lower and upper index i.e. range
let lowerbound = a[i];
let upperbound = b[i];
// Add 'k[i]' value at this operation to
// whole range
for (let j = lowerbound; j <= upperbound; j++)
arr[j] += k[i];
}
// Find maximum value after all operations and
// return
let res = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++)
res = Math.max(res, arr[i]);
return res;
}
// Driver code
let n = 5;
let a = [0, 1, 2];
let b = [1, 4, 3];
// value of k to be added at each operation
let k = [100, 100, 100];
console.log("Maximum value after 'm' operations is " + findMax(n, a, b, k));
OutputMaximum value after 'm' operations is 200
Time Complexity: O(m * max(range)). Here max(range) means maximum elements to which k is added in a single operation.
Auxiliary space: O(n)
[Expected Approach] - Using Prefix Sum
The idea is similar to this post.
Perform two things in a single operation:
- Add k-value to the only lower_bound of a range.
- Reduce the upper_bound + 1 index by a k-value.
After all operations, add all values, check the maximum sum, and print the maximum sum.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find maximum value after 'm' operations
int findMax(int n, vector<int>& a, vector<int>& b, vector<int>& k)
{
vector<int> arr(n + 1, 0);
// Start performing 'm' operations
for (int i = 0; i < a.size(); i++)
{
// Store lower and upper index i.e. range
int lowerbound = a[i];
int upperbound = b[i];
// Add k to the lower_bound
arr[lowerbound] += k[i];
// Reduce upper_bound+1 indexed value by k
if (upperbound + 1 < arr.size())
arr[upperbound + 1] -= k[i];
}
// Find maximum sum possible from all values
int sum = 0, res = INT_MIN;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
res = max(res, sum);
}
return res;
}
// Driver code
int main()
{
// Number of values
int n = 5;
vector<int> a = {0, 1, 2};
vector<int> b = {1, 4, 3};
vector<int> k = {100, 100, 100};
cout << "Maximum value after 'm' operations is "
<< findMax(n, a, b, k);
return 0;
}
Java
// Import necessary packages
import java.util.*;
// Function to find maximum value after 'm' operations
public class Main {
public static int findMax(int n, int[] a, int[] b, int[] k) {
int[] arr = new int[n + 1];
// Start performing 'm' operations
for (int i = 0; i < a.length; i++) {
// Store lower and upper index i.e. range
int lowerbound = a[i];
int upperbound = b[i];
// Add k to the lower_bound
arr[lowerbound] += k[i];
// Reduce upper_bound+1 indexed value by k
if (upperbound + 1 < arr.length)
arr[upperbound + 1] -= k[i];
}
// Find maximum sum possible from all values
int sum = 0, res = Integer.MIN_VALUE;
for (int i = 0; i < n; ++i) {
sum += arr[i];
res = Math.max(res, sum);
}
return res;
}
// Driver code
public static void main(String[] args) {
// Number of values
int n = 5;
int[] a = {0, 1, 2};
int[] b = {1, 4, 3};
int[] k = {100, 100, 100};
System.out.println("Maximum value after 'm' operations is " + findMax(n, a, b, k));
}
}
Python
# Function to find maximum value after 'm' operations
def find_max(n, a, b, k):
arr = [0] * (n + 1)
# Start performing 'm' operations
for i in range(len(a)):
# Store lower and upper index i.e. range
lowerbound = a[i]
upperbound = b[i]
# Add k to the lower_bound
arr[lowerbound] += k[i]
# Reduce upper_bound+1 indexed value by k
if upperbound + 1 < len(arr):
arr[upperbound + 1] -= k[i]
# Find maximum sum possible from all values
sum = 0
res = float('-inf')
for i in range(n):
sum += arr[i]
res = max(res, sum)
return res
# Driver code
if __name__ == '__main__':
# Number of values
n = 5
a = [0, 1, 2]
b = [1, 4, 3]
k = [100, 100, 100]
print("Maximum value after 'm' operations is ", find_max(n, a, b, k))
C#
// Import necessary packages
using System;
using System.Linq;
// Function to find maximum value after 'm' operations
class GfG {
public static int FindMax(int n, int[] a, int[] b, int[] k) {
int[] arr = new int[n + 1];
// Start performing 'm' operations
for (int i = 0; i < a.Length; i++) {
// Store lower and upper index i.e. range
int lowerbound = a[i];
int upperbound = b[i];
// Add k to the lower_bound
arr[lowerbound] += k[i];
// Reduce upper_bound+1 indexed value by k
if (upperbound + 1 < arr.Length)
arr[upperbound + 1] -= k[i];
}
// Find maximum sum possible from all values
int sum = 0, res = int.MinValue;
for (int i = 0; i < n; ++i) {
sum += arr[i];
res = Math.Max(res, sum);
}
return res;
}
// Driver code
public static void Main(string[] args) {
// Number of values
int n = 5;
int[] a = {0, 1, 2};
int[] b = {1, 4, 3};
int[] k = {100, 100, 100};
Console.WriteLine("Maximum value after 'm' operations is " + FindMax(n, a, b, k));
}
}
JavaScript
// Function to find maximum value after 'm' operations
function findMax(n, a, b, k) {
let arr = new Array(n + 1).fill(0);
// Start performing 'm' operations
for (let i = 0; i < a.length; i++) {
// Store lower and upper index i.e. range
let lowerbound = a[i];
let upperbound = b[i];
// Add k to the lower_bound
arr[lowerbound] += k[i];
// Reduce upper_bound+1 indexed value by k
if (upperbound + 1 < arr.length) {
arr[upperbound + 1] -= k[i];
}
}
// Find maximum sum possible from all values
let sum = 0;
let res = Number.NEGATIVE_INFINITY;
for (let i = 0; i < n; i++) {
sum += arr[i];
res = Math.max(res, sum);
}
return res;
}
// Driver code
const n = 5;
const a = [0, 1, 2];
const b = [1, 4, 3];
const k = [100, 100, 100];
console.log("Maximum value after 'm' operations is ", findMax(n, a, b, k));
OutputMaximum value after 'm' operations is 200
Time complexity: O(m + n)
Auxiliary space: O(n)
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
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
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
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
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read