-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_Manipulation.txt
More file actions
97 lines (65 loc) · 2.55 KB
/
Copy pathArray_Manipulation.txt
File metadata and controls
97 lines (65 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
Array Manipulation
Your Array Manipulation submission got 60.00 points.
Proceed to Interview Preparation Kit
Problem
Submissions
Leaderboard
Discussions
Editorial
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.
Example
Queries are interpreted as follows:
a b k
1 5 3
4 8 7
6 9 1
Add the values of between the indices and inclusive:
index-> 1 2 3 4 5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
The largest value is after all operations are performed.
Function Description
Complete the function arrayManipulation in the editor below.
arrayManipulation has the following parameters:
int n - the number of elements in the array
int queries[q][3] - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.
Returns
int - the maximum value in the resultant array
Input Format
The first line contains two space-separated integers and , the size of the array and the number of operations.
Each of the next lines contains three space-separated integers , and , the left index, right index and summand.
Constraints
Sample Input
5 3
1 2 100
2 5 100
3 4 100
Sample Output
200
Explanation
After the first update the list is 100 100 0 0 0.
After the second update list is 100 200 100 100 100.
After the third update list is 100 200 200 200 100.
The maximum value is 200.
public static long arrayManipulation(int n, List<List<Integer>> q) {
// Write your code here
long a[] = new long [n+1];
long max = 0;
for(int i=0; i<q.size(); i++){
int s = q.get(i).get(0);
int e = q.get(i).get(1);
a[s] = a[s] + q.get(i).get(2);
if((e+1)<a.length)
a[e+1] = a[e+1] - q.get(i).get(2);
}
long x = 0;
for(int j=1; j<a.length; j++){
x = x+a[j];
if(x>max)
max = x;
}
return max;
}
see, you are adding sum to a[p] and adding negative sum at a[q+1]. which make sure that when you add element from a[p] to a[q] sum is added only once and it should be subtracted at a[q+1] as this sum span from p to q only. Rest array element are either 0 or some other input sum. max of addition will be output. refer to above code for p, q, and sum.