
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Range Addition in C++
Suppose we have an array of size n and that is initialized with 0's and we also have a value k, we will perform k update operations. Each operation will be represented as triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc. We have to find the modified array after all k operations were executed.
So, if the input is like length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]], then the output will be [- 2,0,3,5,3]
To solve this, we will follow these steps −
Define an array ret of size n
for initialize i := 0, when i < size of a, update (increase i by 1), do −
l := a[i, 0]
r := a[i, 1] + 1
ret[l] := ret[l] + a[i, 2]
if r < n, then −
ret[r] := ret[r] - a[i, 2]
for initialize i := 1, when i < n, update (increase i by 1), do −
ret[i] := ret[i] + ret[i - 1]
return ret
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto< v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int< getModifiedArray(int n, vector& a) { vector<int< ret(n); for (int i = 0; i < a.size(); i++) { int l = a[i][0]; int r = a[i][1] + 1; ret[l] += a[i][2]; if (r < n) { ret[r] -= a[i][2]; } } for (int i = 1; i < n; i++) { ret[i] += ret[i - 1]; } return ret; } }; main(){ Solution ob; vector<vector<int<> v = {{1,3,2},{2,4,3},{0,2,-2}}; print_vector(ob.getModifiedArray(5,v)); }
Input
5, {{1,3,2},{2,4,3},{0,2,-2}}
Output
[-2, 0, 3, 5, 3, ]
- Related Articles
- Range Addition II in C++
- Addition and Concatenation in C#
- Minimum Bracket Addition in C++
- Binary Number System - Overflow in Arithmetic Addition in C/C++?
- Range Module in C++
- Bitwise recursive addition of two integers in C
- Addition and Subtraction of Matrix using pthreads in C/C++
- Binary Indexed Tree: Range Update and Range Queries in C++
- Smallest Range II in C++
- Using range in switch case in C/C++
- How to perform Matrix Addition using C#?
- Range Sum Query - Immutables in C++
- Range-based for loop in C++
- Count of Range Sum in C++
- Mean of range in array in C++
