Find the increased sum of the Array after P operations
Last Updated :
01 Oct, 2023
Given an array arr[] of non-negative integers of size N and an integer P. Neighboring values of every non-zero element are incremented by 2 in each operation, the task is to find the increased sum of the array after P operations.
Examples:
Input: arr[] = {0, 5, 0, 4, 0}, P = 2
Output: 24
Explanation: Operation 1 --> [2, 5, 4, 4, 2] total sum is 17.
Operation 2 --> [4, 9, 8, 8, 4] total sum is 33.
So at the end of 2nd operation the sum of the array is 33. Therefore, the increased value is 33-9 (initial sum) = 24.
Input: arr[] = {2, 5, 0, 7, 0}, P = 4
Output: 58
Approach: To solve the problem follow the below observations:
In order, to get the increased sum of the array we can start finding out what will be the increased value of a particular element. So if we know the increased value of all elements in the array we can sum it up to get the increased sum of the array.
- We know from each operation the value of the particular element is getting increased then we can simply apply the following formula. Let the element starts increasing from the Xth operation then,
- increased value = 2 * (P - X + 1)
- In order to find from which operation exactly the elements start increasing, we can divide this subtask into two steps:
- If the current element is zero,
- since the current is zero, we need to search for a non-zero value on its left and on its right as well. This can be achieved by keeping a prefix and suffix array to store the left and right side non-zero element position from the current element.
- If an element exists on the left side then 2 * (P - current_position + prefix[i] + 1).
- If an element exists on the right side then 2 * (P - suffix[i] + current_position + 1).
- If the current element is non-zero,
- If the (i-1)th element exists and it is a non-zero element then the present element will be incremented by 2*P from its left neighbor and the same applies to the right neighbor as well.
- If the (i-1)th element exists and it is a having a value of zero, then the present element will get incremented from the 2nd operation because, on the first operation, it will be incremented to 2 by the current element (since the current element is non-zero), the present element will be incremented by 2*(P-1) and the same applies to the right neighbor as well.
Below are the steps for the above approach:
- Declare prefix and suffix arrays and initialize both arrays with -1.
- Build both arrays by iterating over array A.
- If the present element is zero, check for the left side positive element, if exists increment the answer by 2 * (P - current_position + prefix[i] + 1).
- If the present element is zero, check for the right side positive element, if exists increment the answer by 2 * (P - suffix[i] + current_position + 1).
- Else if the present element is non-zero, check if the left neighbor exists, if exists check if it is positive or not.
- if positive, increment the answer by 2*P.
- else increment the answer by 2*(P-1).
- Else if the present element is non-zero, check if the left neighbor exists, if exists check if it is positive or not.
- if positive, increment the answer by 2*P.
- else increment the answer by 2*(P-1).
Below is the code for the above approach:
C++
#include <iostream>
#include <algorithm>
using namespace std;
int findIncreasedSum(int A[], int N, int P) {
int prefix[N];
int suffix[N];
// Initializing prefix and suffix arrays
for (int i = 0; i < N; i++) {
prefix[i] = -1;
suffix[i] = -1;
}
// Initializing ans to zero
int ans = 0;
// Building the prefix array
for (int i = 1; i < N; i++) {
if (A[i - 1] > 0) {
prefix[i] = i - 1;
} else {
prefix[i] = prefix[i - 1];
}
}
// Building the suffix array
for (int i = N - 2; i >= 0; i--) {
if (A[i + 1] > 0) {
suffix[i] = i + 1;
} else {
suffix[i] = suffix[i + 1];
}
}
for (int i = 0; i < N; i++) {
// If the current element is zero
if (A[i] == 0) {
// Checking if there is a left neighbor
if (i > 0) {
// Checking if there is a left positive element
if (prefix[i] != -1) {
ans += 2 * max(0, P - i + prefix[i] + 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1) {
// Checking if there is a right positive element
if (suffix[i] != -1) {
ans += 2 * max(P - suffix[i] + i + 1, 0);
}
}
} else {
// Checking if there is a left neighbor
if (i > 0) {
// Checking if the left element is non-zero or not
if (A[i - 1] > 0) {
ans += 2 * P;
} else {
ans += 2 * (P - 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1) {
// Checking if the right element is non-zero or not
if (A[i + 1] > 0) {
ans += 2 * P;
} else {
ans += 2 * (P - 1);
}
}
}
}
return ans;
}
int main() {
int N = 5;
int P = 2;
int A[] = {0, 5, 0, 4, 0};
// Function call
cout << findIncreasedSum(A, N, P) << endl;
return 0;
}
Java
import java.util.Arrays;
class GFG {
public static int findIncreasedSum(int[] A, int N, int P) {
int[] prefix = new int[N];
int[] suffix = new int[N];
// Initializing prefix and suffix arrays
Arrays.fill(prefix, -1);
Arrays.fill(suffix, -1);
// Initializing ans to zero
int ans = 0;
// Building the prefix array
for (int i = 1; i < N; i++) {
if (A[i - 1] > 0) {
prefix[i] = i - 1;
} else {
prefix[i] = prefix[i - 1];
}
}
// Building the suffix array
for (int i = N - 2; i >= 0; i--) {
if (A[i + 1] > 0) {
suffix[i] = i + 1;
} else {
suffix[i] = suffix[i + 1];
}
}
for (int i = 0; i < N; i++) {
// If the current element is zero
if (A[i] == 0) {
// Checking if there is a left neighbor
if (i > 0) {
// Checking if there is a left positive element
if (prefix[i] != -1) {
ans += 2 * Math.max(0, P - i + prefix[i] + 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1) {
// Checking if there is a right positive element
if (suffix[i] != -1) {
ans += 2 * Math.max(P - suffix[i] + i + 1, 0);
}
}
} else {
// Checking if there is a left neighbor
if (i > 0) {
// Checking if the left element is non-zero or not
if (A[i - 1] > 0) {
ans += 2 * P;
} else {
ans += 2 * (P - 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1) {
// Checking if the right element is non-zero or not
if (A[i + 1] > 0) {
ans += 2 * P;
} else {
ans += 2 * (P - 1);
}
}
}
}
return ans;
}
public static void main(String[] args) {
int N = 5;
int P = 2;
int[] A = {0, 5, 0, 4, 0};
// Function call
System.out.println(findIncreasedSum(A, N, P));
}
}
Python3
def findIncreasedSum(A, N, P):
'''
Created prefix and suffix arrays
and initialise with -1 If prefix[i]
is -1 then it means there is no
postive element for the current
element to its left Same holds
for suffix array as well. Else
prefix[i] or suffix[i] will
represent the position of left
positive and postive element
for the current element
respectively.
'''
prefix = [-1]*N
suffix = [-1]*N
# Initialing ans to zero.
ans = 0
# Building the prefix array
for i in range(1, N):
if(A[i - 1] > 0):
prefix[i] = i - 1
else:
prefix[i] = prefix[i-1]
# Building the suffix array
for i in range(N-2, -1, -1):
if(A[i + 1] > 0):
suffix[i] = i + 1
else:
suffix[i] = suffix[i + 1]
for i in range(N):
# If the present is Zero.
if A[i] == 0:
# Checking if there is
# left neighbour
if i > 0:
# Checking if there is
# left positive element
# exists or not
if prefix[i] != -1:
ans += 2*(max(0, P - i + prefix[i] + 1))
# Checking if there is
# right neighbour
if i < N:
# Checking if there is
# right positive element
# exists or not
if suffix[i] != -1:
ans += 2*(max(P - suffix[i] + i + 1, 0))
else:
# Checking if there is
# left neighbour
if i > 0:
# Checking if there is
# left element is non-zero
# or not
if A[i-1] > 0:
ans += 2 * P
else:
ans += 2*(P-1)
# Checking if there is
# right neighbour
if i < N-1:
# Checking if there is
# right element is
# non-zero or not
if A[i + 1] > 0:
ans += 2 * P
else:
ans += 2*(P-1)
return ans
N, P = 5, 2
A = [0, 5, 0, 4, 0]
# Funtion call
print(findIncreasedSum(A, N, P))
C#
using System;
class Program
{
static int FindIncreasedSum(int[] A, int N, int P)
{
int[] prefix = new int[N];
int[] suffix = new int[N];
// Initializing prefix and suffix arrays
for (int i = 0; i < N; i++)
{
prefix[i] = -1;
suffix[i] = -1;
}
// Initializing ans to zero
int ans = 0;
// Building the prefix array
for (int i = 1; i < N; i++)
{
if (A[i - 1] > 0)
{
prefix[i] = i - 1;
}
else
{
prefix[i] = prefix[i - 1];
}
}
// Building the suffix array
for (int i = N - 2; i >= 0; i--)
{
if (A[i + 1] > 0)
{
suffix[i] = i + 1;
}
else
{
suffix[i] = suffix[i + 1];
}
}
for (int i = 0; i < N; i++)
{
// If the current element is zero
if (A[i] == 0)
{
// Checking if there is a left neighbor
if (i > 0)
{
// Checking if there is a left positive element
if (prefix[i] != -1)
{
ans += 2 * Math.Max(0, P - i + prefix[i] + 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1)
{
// Checking if there is a right positive element
if (suffix[i] != -1)
{
ans += 2 * Math.Max(P - suffix[i] + i + 1, 0);
}
}
}
else
{
// Checking if there is a left neighbor
if (i > 0)
{
// Checking if the left element is non-zero or not
if (A[i - 1] > 0)
{
ans += 2 * P;
}
else
{
ans += 2 * (P - 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1)
{
// Checking if the right element is non-zero or not
if (A[i + 1] > 0)
{
ans += 2 * P;
}
else
{
ans += 2 * (P - 1);
}
}
}
}
return ans;
}
// Driver code
static void Main()
{
int N = 5;
int P = 2;
int[] A = { 0, 5, 0, 4, 0 };
Console.WriteLine(FindIncreasedSum(A, N, P));
}
}
JavaScript
function findIncreasedSum(A, N, P) {
let prefix = new Array(N);
let suffix = new Array(N);
// Initializing prefix and suffix arrays
for (let i = 0; i < N; i++) {
prefix[i] = -1;
suffix[i] = -1;
}
// Initializing ans to zero
let ans = 0;
// Building the prefix array
for (let i = 1; i < N; i++) {
if (A[i - 1] > 0) {
prefix[i] = i - 1;
} else {
prefix[i] = prefix[i - 1];
}
}
// Building the suffix array
for (let i = N - 2; i >= 0; i--) {
if (A[i + 1] > 0) {
suffix[i] = i + 1;
} else {
suffix[i] = suffix[i + 1];
}
}
for (let i = 0; i < N; i++) {
// If the current element is zero
if (A[i] == 0) {
// Checking if there is a left neighbor
if (i > 0) {
// Checking if there is a left positive element
if (prefix[i] != -1) {
ans += 2 * Math.max(0, P - i + prefix[i] + 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1) {
// Checking if there is a right positive element
if (suffix[i] != -1) {
ans += 2 * Math.max(P - suffix[i] + i + 1, 0);
}
}
} else {
// Checking if there is a left neighbor
if (i > 0) {
// Checking if the left element is non-zero or not
if (A[i - 1] > 0) {
ans += 2 * P;
} else {
ans += 2 * (P - 1);
}
}
// Checking if there is a right neighbor
if (i < N - 1) {
// Checking if the right element is non-zero or not
if (A[i + 1] > 0) {
ans += 2 * P;
} else {
ans += 2 * (P - 1);
}
}
}
}
return ans;
}
// Function call
let N = 5;
let P = 2;
let A = [0, 5, 0, 4, 0];
console.log(findIncreasedSum(A, N, P));
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem