forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefix_Sum.java
More file actions
55 lines (33 loc) · 1.31 KB
/
Prefix_Sum.java
File metadata and controls
55 lines (33 loc) · 1.31 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
import java.util.*;
public class Prefix_Sum {
public static void main(String[] args) {
Scanner fs = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
System.out.println("Enter 5 integer elements separated by spaces to be added in the list");
for(int i=0 ; i<5 ; i++){
int inp = fs.nextInt();
list.add(inp);
}
List<Integer> prefixSumList = new ArrayList<>();
for(int i=0 ; i<5 ; i++){
if(i==0){
/* first element of list is first element of prefix sum
list as there is no previous sum before it */
prefixSumList.add(list.get(0));
}else{
/* Variable name used are self explanatory to
the idea of prefix sum array
*/
int currentValue = list.get(i);
int previousSum = prefixSumList.get(i-1);
int currentSum = currentValue + previousSum;
// currentSum is the running sun till index i
prefixSumList.add(currentSum);
}
}
System.out.println("Printing the prefix sum for given input :- ");
for(int i=0 ; i<5 ; i++){
System.out.print(prefixSumList.get(i)+" ");
}
}
}