Java Program to Compute the Running Total of a List
Last Updated :
06 Sep, 2022
A List is an ordered sequence of elements stored together to form a collection. A list is a structure to perform both positional access and index-based retrieval of the elements. Lists can be used to store duplicate as well as null elements. Running Total of a sequence of the elements is the summation of the previous sum of the elements and the current integer value received. Lists can be declared and created using an in-built interface <<java.util>>
Storing the first index element of the list into the running total as it is. The previous sum of the elements is initialized to the first index element of this list. And then, with each new element, we add it to the previous sum. This updated sum value becomes the running total until the corresponding index. It is then added to the running total list. Below the procedure is described:
Procedure: Steps followed to compute sum in list
- Step 1: Declaring list for storing running total.
- Step 2: Copy the first element of the original list to the running total List.
- Step 3: Initially, declaring sum to the 0th element of the List.
- Step 4: Iterating over the list starting with the 1st index of List.
- Step 5: Adding the current element to the previous sum.
- Step 6: Copying the previous sum to the running total sum.
- Step 7: Iterating over the elements of the running total List using hasNext() method which holds true till there is a single element remaining in the List.
- Step 8: Print the List which will be running the total List.
Implementation: The following java program is used to illustrate the computation of the running total of the list of elements.
Example:
Java
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add( 2 );
list.add( 4 );
list.add( 6 );
list.add( 8 );
list.add( 10 );
list.add( 12 );
System.out.print( "Original List : " );
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " " );
}
List<Integer> runningtotal
= new ArrayList<Integer>();
runningtotal.add(list.get( 0 ));
int prev_sum = list.get( 0 );
int i = 1 ;
while (i < list.size()) {
prev_sum += list.get(i);
runningtotal.add(prev_sum);
i++;
}
System.out.println();
System.out.print( "Running total List of Original List: " );
iterator = runningtotal.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " " );
}
}
}
|
Output
Original List : 2 4 6 8 10 12
Running total List of Original List: 2 6 12 20 30 42
Time complexity: O(N) where N is the size of the given list.
Auxiliary space: O(N), for storing the running sum of the list.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...