Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum sum of all elements of array after performing given operations
Next article icon

Maximum value in an array after m range increment operations

Last Updated : 06 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)); 

Output
Maximum 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: 

  1. Add k-value to the only lower_bound of a range. 
  2. 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)); 

Output
Maximum value after 'm' operations is 200

Time complexity: O(m + n)
Auxiliary space: O(n)



Next Article
Maximum sum of all elements of array after performing given operations

S

Sahil Chhabra
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • FactSet
  • prefix-sum
Practice Tags :
  • FactSet
  • Arrays
  • Mathematical
  • prefix-sum

Similar Reads

  • For each Array index find the maximum value among all M operations
    Given an array arr[] of size N initially filled with 0 and another array Positions[] of size M, the task is to return the maximum value for each index after performing the following M operations: Make the value at index Positions[i] equal to 0All the numbers to the right of Positions[i] will be one
    6 min read
  • Maximum value obtained by performing given operations in an Array
    Given an array arr[], the task is to find out the maximum obtainable value. The user is allowed to add or multiply the two consecutive elements. However, there has to be at least one addition operation between two multiplication operations (i.e), two consecutive multiplication operations are not all
    11 min read
  • Maximum sum of all elements of array after performing given operations
    Given an array of integers. The task is to find the maximum sum of all the elements of the array after performing the given two operations once each. The operations are: 1. Select some(possibly none) continuous elements from the beginning of the array and multiply by -1. 2. Select some(possibly none
    7 min read
  • Maximum possible Array sum after performing given operations
    Given array arr[] of positive integers, an integer Q, and arrays X[] and Y[] of size Q. For each element in arrays X[] and Y[], we can perform the below operations: For each query from array X[] and Y[], select at most X[i] elements from array arr[] and replace all the selected elements with integer
    9 min read
  • Maximum occurred integers after M circular operations in given range
    Given an integer N and an array arr[] consisting of M integers from the range [1, N]. (M - 1) operations need to performed. In every ith operation, traverse every consecutive elements in the range [1, N] from arr[i] to arr[i + 1] circularly. The task is to print the most visited elements in sorted o
    8 min read
  • Sum of Array maximums after K operations by reducing max element to its half
    Given an array arr[] of N integers and an integer K, the task is to find the sum of maximum of the array possible wherein each operation the current maximum of the array is replaced with its half. Example: Input: arr[] = {2, 4, 6, 8, 10}, K = 5Output: 33Explanation: In 1st operation, the maximum of
    6 min read
  • Maximise minimum element possible in Array after performing given operations
    Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. F
    11 min read
  • Find maximum in an array without using Relational Operators
    Given an array A[] of non-negative integers, find the maximum in the array without using Relational Operator. Examples: Input : A[] = {2, 3, 1, 4, 5}Output : 5Input : A[] = {23, 17, 93}Output : 93We use repeated subtraction to find out the maximum. To find maximum between two numbers, we take a vari
    9 min read
  • Maximum product of an Array after subtracting 1 from any element N times
    Given an array arr[] of positive integers of size M and an integer N, the task is to maximize the product of array after subtracting 1 from any element N number of times Examples: Input: M = 5, arr[] = {5, 1, 7, 8, 3}, N = 2Output: 630Explanation: After subtracting 1 from arr[3] 2 times, array becom
    5 min read
  • Maximum subarray sum in an array created after repeated concatenation
    Given an array and a number k, find the largest sum of contiguous array in the modified array which is formed by repeating the given array k times. Examples : Input : arr[] = {-1, 10, 20}, k = 2Output : 59After concatenating array twice, we get {-1, 10, 20, -1, 10, 20} which has maximum subarray sum
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences